Coverage Report

Created: 2023-05-28 01:35

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.89.6 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - Read FAQ at http://dearimgui.com/faq
6
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
7
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
8
// Read imgui.cpp for details, links and comments.
9
10
// Resources:
11
// - FAQ                   http://dearimgui.com/faq
12
// - Homepage & latest     https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/5886 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17
// - Issues & support      https://github.com/ocornut/imgui/issues
18
19
// Getting Started?
20
// - For first-time users having issues compiling/linking/running or issues loading fonts:
21
//   please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22
23
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
24
// See LICENSE.txt for copyright and licensing details (standard MIT License).
25
// This library is free but needs your support to sustain development and maintenance.
26
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
27
// Individuals: you can support continued development via donations. See docs/README or web page.
28
29
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
30
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
31
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
32
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
33
// to a better solution or official support for them.
34
35
/*
36
37
Index of this file:
38
39
DOCUMENTATION
40
41
- MISSION STATEMENT
42
- CONTROLS GUIDE
43
- PROGRAMMER GUIDE
44
  - READ FIRST
45
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
46
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
47
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
48
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
49
- API BREAKING CHANGES (read me when you update!)
50
- FREQUENTLY ASKED QUESTIONS (FAQ)
51
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
52
53
CODE
54
(search for "[SECTION]" in the code to find them)
55
56
// [SECTION] INCLUDES
57
// [SECTION] FORWARD DECLARATIONS
58
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
59
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
60
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
61
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
62
// [SECTION] MISC HELPERS/UTILITIES (File functions)
63
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
64
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
65
// [SECTION] ImGuiStorage
66
// [SECTION] ImGuiTextFilter
67
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
68
// [SECTION] ImGuiListClipper
69
// [SECTION] STYLING
70
// [SECTION] RENDER HELPERS
71
// [SECTION] INITIALIZATION, SHUTDOWN
72
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
73
// [SECTION] INPUTS
74
// [SECTION] ERROR CHECKING
75
// [SECTION] LAYOUT
76
// [SECTION] SCROLLING
77
// [SECTION] TOOLTIPS
78
// [SECTION] POPUPS
79
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
80
// [SECTION] DRAG AND DROP
81
// [SECTION] LOGGING/CAPTURING
82
// [SECTION] SETTINGS
83
// [SECTION] LOCALIZATION
84
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
85
// [SECTION] DOCKING
86
// [SECTION] PLATFORM DEPENDENT HELPERS
87
// [SECTION] METRICS/DEBUGGER WINDOW
88
// [SECTION] DEBUG LOG WINDOW
89
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
90
91
*/
92
93
//-----------------------------------------------------------------------------
94
// DOCUMENTATION
95
//-----------------------------------------------------------------------------
96
97
/*
98
99
 MISSION STATEMENT
100
 =================
101
102
 - Easy to use to create code-driven and data-driven tools.
103
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
104
 - Easy to hack and improve.
105
 - Minimize setup and maintenance.
106
 - Minimize state storage on user side.
107
 - Minimize state synchronization.
108
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
109
 - Efficient runtime and memory consumption.
110
111
 Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
112
113
 - Doesn't look fancy, doesn't animate.
114
 - Limited layout features, intricate layouts are typically crafted in code.
115
116
117
 CONTROLS GUIDE
118
 ==============
119
120
 - MOUSE CONTROLS
121
   - Mouse wheel:                   Scroll vertically.
122
   - SHIFT+Mouse wheel:             Scroll horizontally.
123
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
124
   - Click ^, Double-Click title:   Collapse window.
125
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
126
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
127
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
128
129
 - TEXT EDITOR
130
   - Hold SHIFT or Drag Mouse:      Select text.
131
   - CTRL+Left/Right:               Word jump.
132
   - CTRL+Shift+Left/Right:         Select words.
133
   - CTRL+A or Double-Click:        Select All.
134
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
135
   - CTRL+Z, CTRL+Y:                Undo, Redo.
136
   - ESCAPE:                        Revert text to its original value.
137
   - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
138
139
 - KEYBOARD CONTROLS
140
   - Basic:
141
     - Tab, SHIFT+Tab               Cycle through text editable fields.
142
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
143
     - CTRL+Click                   Input text into a Slider or Drag widget.
144
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
145
     - Tab, SHIFT+Tab:              Cycle through every items.
146
     - Arrow keys                   Move through items using directional navigation. Tweak value.
147
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
148
     - Enter                        Activate item (prefer text input when possible).
149
     - Space                        Activate item (prefer tweaking with arrows when possible).
150
     - Escape                       Deactivate item, leave child window, close popup.
151
     - Page Up, Page Down           Previous page, next page.
152
     - Home, End                    Scroll to top, scroll to bottom.
153
     - Alt                          Toggle between scrolling layer and menu layer.
154
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
155
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
156
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
157
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
158
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
159
160
 - GAMEPAD CONTROLS
161
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
162
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
163
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
164
   - Backend support: backend needs to:
165
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
166
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
167
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
168
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
169
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
170
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
171
172
 - REMOTE INPUTS SHARING & MOUSE EMULATION
173
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
174
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
175
     in order to share your PC mouse/keyboard.
176
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
177
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
178
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
179
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
180
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
181
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
182
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
183
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
184
185
186
 PROGRAMMER GUIDE
187
 ================
188
189
 READ FIRST
190
 ----------
191
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
192
 - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
193
   destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
194
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
195
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
196
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
197
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
198
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
199
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
200
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
201
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
202
 - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
203
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
204
   If you get an assert, read the messages and comments around the assert.
205
 - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
206
 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
207
   See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
208
   However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
209
 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
210
211
212
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
213
 ----------------------------------------------
214
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
215
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
216
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
217
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
218
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
219
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
220
   likely be a comment about it. Please report any issue to the GitHub page!
221
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
222
 - Try to keep your copy of Dear ImGui reasonably up to date.
223
224
225
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
226
 ---------------------------------------------------------------
227
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
228
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
229
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
230
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
231
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
232
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
233
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
234
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
235
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
236
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
237
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
238
239
240
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
241
 --------------------------------------
242
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
243
 The sub-folders in examples/ contain examples applications following this structure.
244
245
     // Application init: create a dear imgui context, setup some options, load fonts
246
     ImGui::CreateContext();
247
     ImGuiIO& io = ImGui::GetIO();
248
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
249
     // TODO: Fill optional fields of the io structure later.
250
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
251
252
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
253
     ImGui_ImplWin32_Init(hwnd);
254
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
255
256
     // Application main loop
257
     while (true)
258
     {
259
         // Feed inputs to dear imgui, start new frame
260
         ImGui_ImplDX11_NewFrame();
261
         ImGui_ImplWin32_NewFrame();
262
         ImGui::NewFrame();
263
264
         // Any application code here
265
         ImGui::Text("Hello, world!");
266
267
         // Render dear imgui into screen
268
         ImGui::Render();
269
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
270
         g_pSwapChain->Present(1, 0);
271
     }
272
273
     // Shutdown
274
     ImGui_ImplDX11_Shutdown();
275
     ImGui_ImplWin32_Shutdown();
276
     ImGui::DestroyContext();
277
278
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
279
280
     // Application init: create a dear imgui context, setup some options, load fonts
281
     ImGui::CreateContext();
282
     ImGuiIO& io = ImGui::GetIO();
283
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
284
     // TODO: Fill optional fields of the io structure later.
285
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
286
287
     // Build and load the texture atlas into a texture
288
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
289
     int width, height;
290
     unsigned char* pixels = nullptr;
291
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
292
293
     // At this point you've got the texture data and you need to upload that to your graphic system:
294
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
295
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
296
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
297
     io.Fonts->SetTexID((void*)texture);
298
299
     // Application main loop
300
     while (true)
301
     {
302
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
303
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
304
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
305
        io.DisplaySize.x = 1920.0f;             // set the current display width
306
        io.DisplaySize.y = 1280.0f;             // set the current display height here
307
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
308
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
309
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
310
311
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
312
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
313
        ImGui::NewFrame();
314
315
        // Most of your application code here
316
        ImGui::Text("Hello, world!");
317
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
318
        MyGameRender(); // may use any Dear ImGui functions as well!
319
320
        // Render dear imgui, swap buffers
321
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
322
        ImGui::EndFrame();
323
        ImGui::Render();
324
        ImDrawData* draw_data = ImGui::GetDrawData();
325
        MyImGuiRenderFunction(draw_data);
326
        SwapBuffers();
327
     }
328
329
     // Shutdown
330
     ImGui::DestroyContext();
331
332
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
333
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
334
 Please read the FAQ and example applications for details about this!
335
336
337
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
338
 ---------------------------------------------
339
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
340
341
    void MyImGuiRenderFunction(ImDrawData* draw_data)
342
    {
343
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
344
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
345
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
346
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
347
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
348
       ImVec2 clip_off = draw_data->DisplayPos;
349
       for (int n = 0; n < draw_data->CmdListsCount; n++)
350
       {
351
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
352
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
353
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
354
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
355
          {
356
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
357
             if (pcmd->UserCallback)
358
             {
359
                 pcmd->UserCallback(cmd_list, pcmd);
360
             }
361
             else
362
             {
363
                 // Project scissor/clipping rectangles into framebuffer space
364
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
365
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
366
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
367
                     continue;
368
369
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
370
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
371
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
372
                 // - Clipping coordinates are provided in imgui coordinates space:
373
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
374
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
375
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
376
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
377
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
378
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
379
380
                 // The texture for the draw call is specified by pcmd->GetTexID().
381
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
382
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
383
384
                 // Render 'pcmd->ElemCount/3' indexed triangles.
385
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
386
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
387
             }
388
          }
389
       }
390
    }
391
392
393
 API BREAKING CHANGES
394
 ====================
395
396
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
397
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
398
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
399
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
400
401
(Docking/Viewport Branch)
402
 - 2023/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
403
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
404
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
405
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
406
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
407
408
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
409
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
410
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
411
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
412
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
413
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
414
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
415
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
416
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
417
                         it has been frequently requested by people to use our own. We had an opt-in define which was
418
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
419
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
420
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
421
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
422
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
423
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
424
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
425
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
426
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
427
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
428
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
429
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
430
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
431
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
432
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
433
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
434
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
435
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
436
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
437
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
438
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
439
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
440
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
441
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
442
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
443
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
444
                         - previously this would make the window content size ~200x200:
445
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
446
                         - instead, please submit an item:
447
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
448
                         - alternative:
449
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
450
                         - content size is now only extended when submitting an item!
451
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
452
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
453
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
454
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
455
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
456
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
457
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
458
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
459
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
460
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
461
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
462
                        - Official backends from 1.87+                  -> no issue.
463
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
464
                        - Custom backends not writing to io.NavInputs[] -> no issue.
465
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
466
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
467
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
468
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
469
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
470
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
471
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
472
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
473
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
474
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
475
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
476
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
477
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
478
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
479
                       read https://github.com/ocornut/imgui/issues/4921 for details.
480
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
481
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
482
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
483
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
484
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
485
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
486
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
487
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
488
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
489
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
490
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
491
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
492
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
493
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
494
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
495
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
496
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
497
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
498
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
499
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
500
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
501
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
502
                        - if you are using official backends from the source tree: you have nothing to do.
503
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
504
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
505
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
506
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
507
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
508
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
509
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
510
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
511
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
512
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
513
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
514
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
515
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
516
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
517
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
518
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
519
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
520
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
521
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
522
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
523
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
524
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
525
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
526
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
527
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
528
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
529
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
530
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
531
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
532
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
533
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
534
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
535
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
536
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
537
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
538
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
539
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
540
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
541
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
542
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
543
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
544
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
545
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
546
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
547
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
548
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
549
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
550
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
551
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
552
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
553
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
554
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
555
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
556
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
557
                       - if you omitted the 'power' parameter (likely!), you are not affected.
558
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
559
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
560
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
561
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
562
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
563
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
564
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
565
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
566
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
567
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
568
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
569
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
570
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
571
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
572
                       - ShowTestWindow()                    -> use ShowDemoWindow()
573
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
574
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
575
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
576
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
577
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
578
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
579
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
580
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
581
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
582
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
583
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
584
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
585
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
586
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
587
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
588
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
589
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
590
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
591
                       - ImFont::Glyph                       -> use ImFontGlyph
592
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
593
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
594
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
595
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
596
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
597
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
598
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
599
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
600
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
601
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
602
                       Please reach out if you are affected.
603
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
604
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
605
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
606
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
607
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
608
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
609
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
610
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
611
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
612
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
613
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
614
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
615
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
616
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
617
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
618
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
619
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
620
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
621
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
622
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
623
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
624
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
625
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
626
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
627
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
628
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
629
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
630
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
631
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
632
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
633
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
634
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
635
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
636
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
637
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
638
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
639
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
640
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
641
                       consistent with other functions. Kept redirection functions (will obsolete).
642
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
643
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
644
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
645
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
646
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
647
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
648
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
649
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
650
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
651
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
652
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
653
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
654
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
655
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
656
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
657
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
658
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
659
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
660
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
661
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
662
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
663
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
664
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
665
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
666
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
667
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
668
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
669
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
670
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
671
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
672
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
673
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
674
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
675
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
676
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
677
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
678
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
679
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
680
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
681
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
682
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
683
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
684
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
685
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
686
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
687
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
688
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
689
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
690
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
691
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
692
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
693
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
694
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
695
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
696
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
697
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
698
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
699
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
700
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
701
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
702
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
703
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
704
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
705
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
706
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
707
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
708
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
709
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
710
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
711
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
712
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
713
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
714
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
715
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
716
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
717
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
718
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
719
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
720
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
721
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
722
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
723
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
724
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
725
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
726
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
727
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
728
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
729
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
730
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
731
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
732
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
733
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
734
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
735
                     - the signature of the io.RenderDrawListsFn handler has changed!
736
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
737
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
738
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
739
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
740
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
741
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
742
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
743
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
744
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
745
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
746
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
747
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
748
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
749
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
750
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
751
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
752
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
753
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
754
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
755
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
756
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
757
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
758
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
759
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
760
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
761
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
762
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
763
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
764
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
765
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
766
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
767
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
768
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
769
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
770
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
771
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
772
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
773
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
774
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
775
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
776
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
777
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
778
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
779
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
780
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
781
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
782
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
783
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
784
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
785
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
786
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
787
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
788
789
790
 FREQUENTLY ASKED QUESTIONS (FAQ)
791
 ================================
792
793
 Read all answers online:
794
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
795
 Read all answers locally (with a text editor or ideally a Markdown viewer):
796
   docs/FAQ.md
797
 Some answers are copied down here to facilitate searching in code.
798
799
 Q&A: Basics
800
 ===========
801
802
 Q: Where is the documentation?
803
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
804
    - Run the examples/ and explore them.
805
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
806
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
807
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
808
    - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
809
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
810
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
811
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
812
    - Your programming IDE is your friend, find the type or function declaration to find comments
813
      associated with it.
814
815
 Q: What is this library called?
816
 Q: Which version should I get?
817
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
818
 >> See https://www.dearimgui.com/faq for details.
819
820
 Q&A: Integration
821
 ================
822
823
 Q: How to get started?
824
 A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
825
826
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
827
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
828
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
829
830
 Q. How can I enable keyboard controls?
831
 Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
832
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
833
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
834
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
835
 >> See https://www.dearimgui.com/faq
836
837
 Q&A: Usage
838
 ----------
839
840
 Q: About the ID Stack system..
841
   - Why is my widget not reacting when I click on it?
842
   - How can I have widgets with an empty label?
843
   - How can I have multiple widgets with the same label?
844
   - How can I have multiple windows with the same label?
845
 Q: How can I display an image? What is ImTextureID, how does it work?
846
 Q: How can I use my own math types instead of ImVec2/ImVec4?
847
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
848
 Q: How can I display custom shapes? (using low-level ImDrawList API)
849
 >> See https://www.dearimgui.com/faq
850
851
 Q&A: Fonts, Text
852
 ================
853
854
 Q: How should I handle DPI in my application?
855
 Q: How can I load a different font than the default?
856
 Q: How can I easily use icons in my application?
857
 Q: How can I load multiple fonts?
858
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
859
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
860
861
 Q&A: Concerns
862
 =============
863
864
 Q: Who uses Dear ImGui?
865
 Q: Can you create elaborate/serious tools with Dear ImGui?
866
 Q: Can you reskin the look of Dear ImGui?
867
 Q: Why using C++ (as opposed to C)?
868
 >> See https://www.dearimgui.com/faq
869
870
 Q&A: Community
871
 ==============
872
873
 Q: How can I help?
874
 A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
875
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
876
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
877
    - Individuals: you can support continued development via PayPal donations. See README.
878
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
879
      and see how you want to help and can help!
880
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
881
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
882
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
883
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
884
885
*/
886
887
//-------------------------------------------------------------------------
888
// [SECTION] INCLUDES
889
//-------------------------------------------------------------------------
890
891
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
892
#define _CRT_SECURE_NO_WARNINGS
893
#endif
894
895
#ifndef IMGUI_DEFINE_MATH_OPERATORS
896
#define IMGUI_DEFINE_MATH_OPERATORS
897
#endif
898
899
#include "imgui.h"
900
#ifndef IMGUI_DISABLE
901
#include "imgui_internal.h"
902
903
// System includes
904
#include <stdio.h>      // vsnprintf, sscanf, printf
905
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
906
#include <stddef.h>     // intptr_t
907
#else
908
#include <stdint.h>     // intptr_t
909
#endif
910
911
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
912
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
913
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
914
#endif
915
916
// [Windows] OS specific includes (optional)
917
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
918
#define IMGUI_DISABLE_WIN32_FUNCTIONS
919
#endif
920
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
921
#ifndef WIN32_LEAN_AND_MEAN
922
#define WIN32_LEAN_AND_MEAN
923
#endif
924
#ifndef NOMINMAX
925
#define NOMINMAX
926
#endif
927
#ifndef __MINGW32__
928
#include <Windows.h>        // _wfopen, OpenClipboard
929
#else
930
#include <windows.h>
931
#endif
932
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
933
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
934
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
935
#endif
936
#endif
937
938
// [Apple] OS specific includes
939
#if defined(__APPLE__)
940
#include <TargetConditionals.h>
941
#endif
942
943
// Visual Studio warnings
944
#ifdef _MSC_VER
945
#pragma warning (disable: 4127)             // condition expression is constant
946
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
947
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
948
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
949
#endif
950
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
951
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
952
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
953
#endif
954
955
// Clang/GCC warnings with -Weverything
956
#if defined(__clang__)
957
#if __has_warning("-Wunknown-warning-option")
958
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
959
#endif
960
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
961
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
962
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
963
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
964
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
965
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
966
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
967
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
968
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
969
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
970
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
971
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
972
#elif defined(__GNUC__)
973
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
974
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
975
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
976
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
977
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
978
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
979
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
980
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
981
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
982
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
983
#endif
984
985
// Debug options
986
365k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
987
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
988
#define IMGUI_DEBUG_INI_SETTINGS    0   // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
989
990
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
991
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
992
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
993
994
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
995
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
996
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
997
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
998
999
// Docking
1000
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1001
static const float DOCKING_SPLITTER_SIZE                    = 2.0f;
1002
1003
//-------------------------------------------------------------------------
1004
// [SECTION] FORWARD DECLARATIONS
1005
//-------------------------------------------------------------------------
1006
1007
static void             SetCurrentWindow(ImGuiWindow* window);
1008
static void             FindHoveredWindow();
1009
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1010
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1011
1012
static void             AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
1013
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1014
1015
// Settings
1016
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1017
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1018
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1019
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1020
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1021
1022
// Platform Dependents default implementation for IO functions
1023
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1024
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1025
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1026
1027
namespace ImGui
1028
{
1029
// Navigation
1030
static void             NavUpdate();
1031
static void             NavUpdateWindowing();
1032
static void             NavUpdateWindowingOverlay();
1033
static void             NavUpdateCancelRequest();
1034
static void             NavUpdateCreateMoveRequest();
1035
static void             NavUpdateCreateTabbingRequest();
1036
static float            NavUpdatePageUpPageDown();
1037
static inline void      NavUpdateAnyRequestFlag();
1038
static void             NavUpdateCreateWrappingRequest();
1039
static void             NavEndFrame();
1040
static bool             NavScoreItem(ImGuiNavItemData* result);
1041
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1042
static void             NavProcessItem();
1043
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1044
static ImVec2           NavCalcPreferredRefPos();
1045
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1046
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1047
static void             NavRestoreLayer(ImGuiNavLayer layer);
1048
static void             NavRestoreHighlightAfterMove();
1049
static int              FindWindowFocusIndex(ImGuiWindow* window);
1050
1051
// Error Checking and Debug Tools
1052
static void             ErrorCheckNewFrameSanityChecks();
1053
static void             ErrorCheckEndFrameSanityChecks();
1054
static void             UpdateDebugToolItemPicker();
1055
static void             UpdateDebugToolStackQueries();
1056
1057
// Inputs
1058
static void             UpdateKeyboardInputs();
1059
static void             UpdateMouseInputs();
1060
static void             UpdateMouseWheel();
1061
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1062
1063
// Misc
1064
static void             UpdateSettings();
1065
static bool             UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1066
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1067
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1068
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1069
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1070
static void             RenderDimmedBackgrounds();
1071
1072
// Viewports
1073
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1074
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1075
static void             DestroyViewport(ImGuiViewportP* viewport);
1076
static void             UpdateViewportsNewFrame();
1077
static void             UpdateViewportsEndFrame();
1078
static void             WindowSelectViewport(ImGuiWindow* window);
1079
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1080
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1081
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1082
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1083
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1084
static int              FindPlatformMonitorForRect(const ImRect& r);
1085
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1086
1087
}
1088
1089
//-----------------------------------------------------------------------------
1090
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1091
//-----------------------------------------------------------------------------
1092
1093
// DLL users:
1094
// - Heaps and globals are not shared across DLL boundaries!
1095
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1096
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1097
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1098
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1099
1100
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1101
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1102
//   Change to a different context by calling ImGui::SetCurrentContext().
1103
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1104
//   If you want thread-safety to allow N threads to access N different contexts:
1105
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1106
//         struct ImGuiContext;
1107
//         extern thread_local ImGuiContext* MyImGuiTLS;
1108
//         #define GImGui MyImGuiTLS
1109
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1110
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1111
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1112
// - DLL users: read comments above.
1113
#ifndef GImGui
1114
ImGuiContext*   GImGui = NULL;
1115
#endif
1116
1117
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1118
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1119
// - DLL users: read comments above.
1120
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1121
3.70k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1122
3.55k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1123
#else
1124
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1125
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1126
#endif
1127
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1128
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1129
static void*                GImAllocatorUserData = NULL;
1130
1131
//-----------------------------------------------------------------------------
1132
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1133
//-----------------------------------------------------------------------------
1134
1135
ImGuiStyle::ImGuiStyle()
1136
3
{
1137
3
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1138
3
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1139
3
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1140
3
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1141
3
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1142
3
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1143
3
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1144
3
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1145
3
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1146
3
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1147
3
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1148
3
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1149
3
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1150
3
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1151
3
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1152
3
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1153
3
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1154
3
    CellPadding             = ImVec2(4,2);      // Padding within a table cell
1155
3
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1156
3
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1157
3
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1158
3
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1159
3
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1160
3
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1161
3
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1162
3
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1163
3
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1164
3
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1165
3
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1166
3
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1167
3
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1168
3
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1169
3
    SeparatorTextBorderSize = 3.0f;             // Thickkness of border in SeparatorText()
1170
3
    SeparatorTextAlign      = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1171
3
    SeparatorTextPadding    = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1172
3
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1173
3
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1174
3
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1175
3
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1176
3
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1177
3
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1178
3
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1179
3
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1180
1181
    // Default theme
1182
3
    ImGui::StyleColorsDark(this);
1183
3
}
1184
1185
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1186
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1187
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1188
0
{
1189
0
    WindowPadding = ImFloor(WindowPadding * scale_factor);
1190
0
    WindowRounding = ImFloor(WindowRounding * scale_factor);
1191
0
    WindowMinSize = ImFloor(WindowMinSize * scale_factor);
1192
0
    ChildRounding = ImFloor(ChildRounding * scale_factor);
1193
0
    PopupRounding = ImFloor(PopupRounding * scale_factor);
1194
0
    FramePadding = ImFloor(FramePadding * scale_factor);
1195
0
    FrameRounding = ImFloor(FrameRounding * scale_factor);
1196
0
    ItemSpacing = ImFloor(ItemSpacing * scale_factor);
1197
0
    ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
1198
0
    CellPadding = ImFloor(CellPadding * scale_factor);
1199
0
    TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
1200
0
    IndentSpacing = ImFloor(IndentSpacing * scale_factor);
1201
0
    ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
1202
0
    ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
1203
0
    ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
1204
0
    GrabMinSize = ImFloor(GrabMinSize * scale_factor);
1205
0
    GrabRounding = ImFloor(GrabRounding * scale_factor);
1206
0
    LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
1207
0
    TabRounding = ImFloor(TabRounding * scale_factor);
1208
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1209
0
    SeparatorTextPadding = ImFloor(SeparatorTextPadding * scale_factor);
1210
0
    DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
1211
0
    DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
1212
0
    MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
1213
0
}
1214
1215
ImGuiIO::ImGuiIO()
1216
3
{
1217
    // Most fields are initialized with zero
1218
3
    memset(this, 0, sizeof(*this));
1219
3
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1220
1221
    // Settings
1222
3
    ConfigFlags = ImGuiConfigFlags_None;
1223
3
    BackendFlags = ImGuiBackendFlags_None;
1224
3
    DisplaySize = ImVec2(-1.0f, -1.0f);
1225
3
    DeltaTime = 1.0f / 60.0f;
1226
3
    IniSavingRate = 5.0f;
1227
3
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1228
3
    LogFilename = "imgui_log.txt";
1229
3
    MouseDoubleClickTime = 0.30f;
1230
3
    MouseDoubleClickMaxDist = 6.0f;
1231
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1232
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1233
        KeyMap[i] = -1;
1234
#endif
1235
3
    KeyRepeatDelay = 0.275f;
1236
3
    KeyRepeatRate = 0.050f;
1237
3
    HoverDelayNormal = 0.30f;
1238
3
    HoverDelayShort = 0.10f;
1239
3
    UserData = NULL;
1240
1241
3
    Fonts = NULL;
1242
3
    FontGlobalScale = 1.0f;
1243
3
    FontDefault = NULL;
1244
3
    FontAllowUserScaling = false;
1245
3
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1246
1247
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1248
3
    ConfigDockingNoSplit = false;
1249
3
    ConfigDockingWithShift = false;
1250
3
    ConfigDockingAlwaysTabBar = false;
1251
3
    ConfigDockingTransparentPayload = false;
1252
1253
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1254
3
    ConfigViewportsNoAutoMerge = false;
1255
3
    ConfigViewportsNoTaskBarIcon = false;
1256
3
    ConfigViewportsNoDecoration = true;
1257
3
    ConfigViewportsNoDefaultParent = false;
1258
1259
    // Miscellaneous options
1260
3
    MouseDrawCursor = false;
1261
#ifdef __APPLE__
1262
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1263
#else
1264
3
    ConfigMacOSXBehaviors = false;
1265
3
#endif
1266
3
    ConfigInputTrickleEventQueue = true;
1267
3
    ConfigInputTextCursorBlink = true;
1268
3
    ConfigInputTextEnterKeepActive = false;
1269
3
    ConfigDragClickToInputText = false;
1270
3
    ConfigWindowsResizeFromEdges = true;
1271
3
    ConfigWindowsMoveFromTitleBarOnly = false;
1272
3
    ConfigMemoryCompactTimer = 60.0f;
1273
3
    ConfigDebugBeginReturnValueOnce = false;
1274
3
    ConfigDebugBeginReturnValueLoop = false;
1275
1276
    // Platform Functions
1277
    // Note: Initialize() will setup default clipboard/ime handlers.
1278
3
    BackendPlatformName = BackendRendererName = NULL;
1279
3
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1280
1281
    // Input (NB: we already have memset zero the entire structure!)
1282
3
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1283
3
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1284
3
    MouseSource = ImGuiMouseSource_Mouse;
1285
3
    MouseDragThreshold = 6.0f;
1286
18
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1287
423
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1288
3
    AppAcceptingEvents = true;
1289
3
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1290
3
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1291
3
}
1292
1293
// Pass in translated ASCII characters for text input.
1294
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1295
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1296
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1297
void ImGuiIO::AddInputCharacter(unsigned int c)
1298
22.3k
{
1299
22.3k
    IM_ASSERT(Ctx != NULL);
1300
22.3k
    ImGuiContext& g = *Ctx;
1301
22.3k
    if (c == 0 || !AppAcceptingEvents)
1302
5.94k
        return;
1303
1304
16.4k
    ImGuiInputEvent e;
1305
16.4k
    e.Type = ImGuiInputEventType_Text;
1306
16.4k
    e.Source = ImGuiInputSource_Keyboard;
1307
16.4k
    e.EventId = g.InputEventsNextEventId++;
1308
16.4k
    e.Text.Char = c;
1309
16.4k
    g.InputEventsQueue.push_back(e);
1310
16.4k
}
1311
1312
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1313
// we should save the high surrogate.
1314
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1315
12.7k
{
1316
12.7k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1317
684
        return;
1318
1319
12.1k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1320
2.73k
    {
1321
2.73k
        if (InputQueueSurrogate != 0)
1322
1.04k
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1323
2.73k
        InputQueueSurrogate = c;
1324
2.73k
        return;
1325
2.73k
    }
1326
1327
9.36k
    ImWchar cp = c;
1328
9.36k
    if (InputQueueSurrogate != 0)
1329
1.57k
    {
1330
1.57k
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1331
1.10k
        {
1332
1.10k
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1333
1.10k
        }
1334
470
        else
1335
470
        {
1336
470
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1337
470
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1338
#else
1339
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1340
#endif
1341
470
        }
1342
1343
1.57k
        InputQueueSurrogate = 0;
1344
1.57k
    }
1345
9.36k
    AddInputCharacter((unsigned)cp);
1346
9.36k
}
1347
1348
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1349
151
{
1350
151
    if (!AppAcceptingEvents)
1351
0
        return;
1352
151
    while (*utf8_chars != 0)
1353
0
    {
1354
0
        unsigned int c = 0;
1355
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1356
0
        AddInputCharacter(c);
1357
0
    }
1358
151
}
1359
1360
// FIXME: Perhaps we could clear queued events as well?
1361
void ImGuiIO::ClearInputCharacters()
1362
24.3k
{
1363
24.3k
    InputQueueCharacters.resize(0);
1364
24.3k
}
1365
1366
// FIXME: Perhaps we could clear queued events as well?
1367
void ImGuiIO::ClearInputKeys()
1368
26.5k
{
1369
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1370
    memset(KeysDown, 0, sizeof(KeysDown));
1371
#endif
1372
3.74M
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1373
3.71M
    {
1374
3.71M
        KeysData[n].Down             = false;
1375
3.71M
        KeysData[n].DownDuration     = -1.0f;
1376
3.71M
        KeysData[n].DownDurationPrev = -1.0f;
1377
3.71M
    }
1378
26.5k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1379
26.5k
    KeyMods = ImGuiMod_None;
1380
26.5k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1381
159k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1382
132k
    {
1383
132k
        MouseDown[n] = false;
1384
132k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1385
132k
    }
1386
26.5k
    MouseWheel = MouseWheelH = 0.0f;
1387
26.5k
}
1388
1389
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1390
56.0k
{
1391
56.0k
    ImGuiContext& g = *ctx;
1392
89.9k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1393
48.6k
    {
1394
48.6k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1395
48.6k
        if (e->Type != type)
1396
26.0k
            continue;
1397
22.6k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1398
1.46k
            continue;
1399
21.1k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1400
6.35k
            continue;
1401
14.8k
        return e;
1402
21.1k
    }
1403
41.2k
    return NULL;
1404
56.0k
}
1405
1406
// Queue a new key down/up event.
1407
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1408
// - bool down:          Is the key down? use false to signify a key release.
1409
// - float analog_value: 0.0f..1.0f
1410
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1411
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1412
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1413
11.5k
{
1414
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1415
11.5k
    IM_ASSERT(Ctx != NULL);
1416
11.5k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1417
0
        return;
1418
11.5k
    ImGuiContext& g = *Ctx;
1419
11.5k
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1420
11.5k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1421
11.5k
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1422
1423
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1424
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1425
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1426
    if (BackendUsingLegacyKeyArrays == -1)
1427
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1428
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1429
    BackendUsingLegacyKeyArrays = 0;
1430
#endif
1431
11.5k
    if (ImGui::IsGamepadKey(key))
1432
108
        BackendUsingLegacyNavInputArray = false;
1433
1434
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1435
11.5k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1436
11.5k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1437
11.5k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1438
11.5k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1439
11.5k
    if (latest_key_down == down && latest_key_analog == analog_value)
1440
2.01k
        return;
1441
1442
    // Add event
1443
9.49k
    ImGuiInputEvent e;
1444
9.49k
    e.Type = ImGuiInputEventType_Key;
1445
9.49k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1446
9.49k
    e.EventId = g.InputEventsNextEventId++;
1447
9.49k
    e.Key.Key = key;
1448
9.49k
    e.Key.Down = down;
1449
9.49k
    e.Key.AnalogValue = analog_value;
1450
9.49k
    g.InputEventsQueue.push_back(e);
1451
9.49k
}
1452
1453
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1454
5.68k
{
1455
5.68k
    if (!AppAcceptingEvents)
1456
0
        return;
1457
5.68k
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1458
5.68k
}
1459
1460
// [Optional] Call after AddKeyEvent().
1461
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1462
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1463
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1464
0
{
1465
0
    if (key == ImGuiKey_None)
1466
0
        return;
1467
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1468
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1469
0
    IM_UNUSED(native_keycode);  // Yet unused
1470
0
    IM_UNUSED(native_scancode); // Yet unused
1471
1472
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1473
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1474
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1475
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1476
        return;
1477
    KeyMap[legacy_key] = key;
1478
    KeyMap[key] = legacy_key;
1479
#else
1480
0
    IM_UNUSED(key);
1481
0
    IM_UNUSED(native_legacy_index);
1482
0
#endif
1483
0
}
1484
1485
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1486
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1487
0
{
1488
0
    AppAcceptingEvents = accepting_events;
1489
0
}
1490
1491
// Queue a mouse move event
1492
void ImGuiIO::AddMousePosEvent(float x, float y)
1493
13.8k
{
1494
13.8k
    IM_ASSERT(Ctx != NULL);
1495
13.8k
    ImGuiContext& g = *Ctx;
1496
13.8k
    if (!AppAcceptingEvents)
1497
0
        return;
1498
1499
    // Apply same flooring as UpdateMouseInputs()
1500
13.8k
    ImVec2 pos((x > -FLT_MAX) ? ImFloorSigned(x) : x, (y > -FLT_MAX) ? ImFloorSigned(y) : y);
1501
1502
    // Filter duplicate
1503
13.8k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1504
13.8k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1505
13.8k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1506
3.10k
        return;
1507
1508
10.7k
    ImGuiInputEvent e;
1509
10.7k
    e.Type = ImGuiInputEventType_MousePos;
1510
10.7k
    e.Source = ImGuiInputSource_Mouse;
1511
10.7k
    e.EventId = g.InputEventsNextEventId++;
1512
10.7k
    e.MousePos.PosX = pos.x;
1513
10.7k
    e.MousePos.PosY = pos.y;
1514
10.7k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1515
10.7k
    g.InputEventsQueue.push_back(e);
1516
10.7k
}
1517
1518
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1519
26.6k
{
1520
26.6k
    IM_ASSERT(Ctx != NULL);
1521
26.6k
    ImGuiContext& g = *Ctx;
1522
26.6k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1523
26.6k
    if (!AppAcceptingEvents)
1524
0
        return;
1525
1526
    // Filter duplicate
1527
26.6k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1528
26.6k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1529
26.6k
    if (latest_button_down == down)
1530
10.0k
        return;
1531
1532
16.6k
    ImGuiInputEvent e;
1533
16.6k
    e.Type = ImGuiInputEventType_MouseButton;
1534
16.6k
    e.Source = ImGuiInputSource_Mouse;
1535
16.6k
    e.EventId = g.InputEventsNextEventId++;
1536
16.6k
    e.MouseButton.Button = mouse_button;
1537
16.6k
    e.MouseButton.Down = down;
1538
16.6k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1539
16.6k
    g.InputEventsQueue.push_back(e);
1540
16.6k
}
1541
1542
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1543
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1544
6.54k
{
1545
6.54k
    IM_ASSERT(Ctx != NULL);
1546
6.54k
    ImGuiContext& g = *Ctx;
1547
1548
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1549
6.54k
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1550
312
        return;
1551
1552
6.23k
    ImGuiInputEvent e;
1553
6.23k
    e.Type = ImGuiInputEventType_MouseWheel;
1554
6.23k
    e.Source = ImGuiInputSource_Mouse;
1555
6.23k
    e.EventId = g.InputEventsNextEventId++;
1556
6.23k
    e.MouseWheel.WheelX = wheel_x;
1557
6.23k
    e.MouseWheel.WheelY = wheel_y;
1558
6.23k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1559
6.23k
    g.InputEventsQueue.push_back(e);
1560
6.23k
}
1561
1562
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1563
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1564
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1565
0
{
1566
0
    IM_ASSERT(Ctx != NULL);
1567
0
    ImGuiContext& g = *Ctx;
1568
0
    g.InputEventsNextMouseSource = source;
1569
0
}
1570
1571
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1572
0
{
1573
0
    IM_ASSERT(Ctx != NULL);
1574
0
    ImGuiContext& g = *Ctx;
1575
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1576
0
    if (!AppAcceptingEvents)
1577
0
        return;
1578
1579
    // Filter duplicate
1580
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1581
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1582
0
    if (latest_viewport_id == viewport_id)
1583
0
        return;
1584
1585
0
    ImGuiInputEvent e;
1586
0
    e.Type = ImGuiInputEventType_MouseViewport;
1587
0
    e.Source = ImGuiInputSource_Mouse;
1588
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1589
0
    g.InputEventsQueue.push_back(e);
1590
0
}
1591
1592
void ImGuiIO::AddFocusEvent(bool focused)
1593
4.10k
{
1594
4.10k
    IM_ASSERT(Ctx != NULL);
1595
4.10k
    ImGuiContext& g = *Ctx;
1596
1597
    // Filter duplicate
1598
4.10k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1599
4.10k
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1600
4.10k
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1601
972
        return;
1602
1603
3.13k
    ImGuiInputEvent e;
1604
3.13k
    e.Type = ImGuiInputEventType_Focus;
1605
3.13k
    e.EventId = g.InputEventsNextEventId++;
1606
3.13k
    e.AppFocused.Focused = focused;
1607
3.13k
    g.InputEventsQueue.push_back(e);
1608
3.13k
}
1609
1610
//-----------------------------------------------------------------------------
1611
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1612
//-----------------------------------------------------------------------------
1613
1614
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1615
0
{
1616
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1617
0
    ImVec2 p_last = p1;
1618
0
    ImVec2 p_closest;
1619
0
    float p_closest_dist2 = FLT_MAX;
1620
0
    float t_step = 1.0f / (float)num_segments;
1621
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1622
0
    {
1623
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1624
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1625
0
        float dist2 = ImLengthSqr(p - p_line);
1626
0
        if (dist2 < p_closest_dist2)
1627
0
        {
1628
0
            p_closest = p_line;
1629
0
            p_closest_dist2 = dist2;
1630
0
        }
1631
0
        p_last = p_current;
1632
0
    }
1633
0
    return p_closest;
1634
0
}
1635
1636
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1637
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1638
0
{
1639
0
    float dx = x4 - x1;
1640
0
    float dy = y4 - y1;
1641
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1642
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1643
0
    d2 = (d2 >= 0) ? d2 : -d2;
1644
0
    d3 = (d3 >= 0) ? d3 : -d3;
1645
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1646
0
    {
1647
0
        ImVec2 p_current(x4, y4);
1648
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1649
0
        float dist2 = ImLengthSqr(p - p_line);
1650
0
        if (dist2 < p_closest_dist2)
1651
0
        {
1652
0
            p_closest = p_line;
1653
0
            p_closest_dist2 = dist2;
1654
0
        }
1655
0
        p_last = p_current;
1656
0
    }
1657
0
    else if (level < 10)
1658
0
    {
1659
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1660
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1661
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1662
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1663
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1664
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1665
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1666
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1667
0
    }
1668
0
}
1669
1670
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1671
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1672
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1673
0
{
1674
0
    IM_ASSERT(tess_tol > 0.0f);
1675
0
    ImVec2 p_last = p1;
1676
0
    ImVec2 p_closest;
1677
0
    float p_closest_dist2 = FLT_MAX;
1678
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1679
0
    return p_closest;
1680
0
}
1681
1682
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1683
0
{
1684
0
    ImVec2 ap = p - a;
1685
0
    ImVec2 ab_dir = b - a;
1686
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1687
0
    if (dot < 0.0f)
1688
0
        return a;
1689
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1690
0
    if (dot > ab_len_sqr)
1691
0
        return b;
1692
0
    return a + ab_dir * dot / ab_len_sqr;
1693
0
}
1694
1695
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1696
0
{
1697
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1698
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1699
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1700
0
    return ((b1 == b2) && (b2 == b3));
1701
0
}
1702
1703
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1704
0
{
1705
0
    ImVec2 v0 = b - a;
1706
0
    ImVec2 v1 = c - a;
1707
0
    ImVec2 v2 = p - a;
1708
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1709
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1710
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1711
0
    out_u = 1.0f - out_v - out_w;
1712
0
}
1713
1714
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1715
0
{
1716
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1717
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1718
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1719
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1720
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1721
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1722
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1723
0
    if (m == dist2_ab)
1724
0
        return proj_ab;
1725
0
    if (m == dist2_bc)
1726
0
        return proj_bc;
1727
0
    return proj_ca;
1728
0
}
1729
1730
//-----------------------------------------------------------------------------
1731
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1732
//-----------------------------------------------------------------------------
1733
1734
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1735
int ImStricmp(const char* str1, const char* str2)
1736
0
{
1737
0
    int d;
1738
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1739
0
    return d;
1740
0
}
1741
1742
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1743
0
{
1744
0
    int d = 0;
1745
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1746
0
    return d;
1747
0
}
1748
1749
void ImStrncpy(char* dst, const char* src, size_t count)
1750
18
{
1751
18
    if (count < 1)
1752
0
        return;
1753
18
    if (count > 1)
1754
18
        strncpy(dst, src, count - 1);
1755
18
    dst[count - 1] = 0;
1756
18
}
1757
1758
char* ImStrdup(const char* str)
1759
10
{
1760
10
    size_t len = strlen(str);
1761
10
    void* buf = IM_ALLOC(len + 1);
1762
10
    return (char*)memcpy(buf, (const void*)str, len + 1);
1763
10
}
1764
1765
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1766
0
{
1767
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1768
0
    size_t src_size = strlen(src) + 1;
1769
0
    if (dst_buf_size < src_size)
1770
0
    {
1771
0
        IM_FREE(dst);
1772
0
        dst = (char*)IM_ALLOC(src_size);
1773
0
        if (p_dst_size)
1774
0
            *p_dst_size = src_size;
1775
0
    }
1776
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1777
0
}
1778
1779
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1780
0
{
1781
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1782
0
    return p;
1783
0
}
1784
1785
int ImStrlenW(const ImWchar* str)
1786
0
{
1787
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1788
0
    int n = 0;
1789
0
    while (*str++) n++;
1790
0
    return n;
1791
0
}
1792
1793
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1794
const char* ImStreolRange(const char* str, const char* str_end)
1795
0
{
1796
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1797
0
    return p ? p : str_end;
1798
0
}
1799
1800
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1801
0
{
1802
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1803
0
        buf_mid_line--;
1804
0
    return buf_mid_line;
1805
0
}
1806
1807
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1808
0
{
1809
0
    if (!needle_end)
1810
0
        needle_end = needle + strlen(needle);
1811
1812
0
    const char un0 = (char)ImToUpper(*needle);
1813
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1814
0
    {
1815
0
        if (ImToUpper(*haystack) == un0)
1816
0
        {
1817
0
            const char* b = needle + 1;
1818
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1819
0
                if (ImToUpper(*a) != ImToUpper(*b))
1820
0
                    break;
1821
0
            if (b == needle_end)
1822
0
                return haystack;
1823
0
        }
1824
0
        haystack++;
1825
0
    }
1826
0
    return NULL;
1827
0
}
1828
1829
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1830
void ImStrTrimBlanks(char* buf)
1831
0
{
1832
0
    char* p = buf;
1833
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1834
0
        p++;
1835
0
    char* p_start = p;
1836
0
    while (*p != 0)                         // Find end of string
1837
0
        p++;
1838
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1839
0
        p--;
1840
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1841
0
        memmove(buf, p_start, p - p_start);
1842
0
    buf[p - p_start] = 0;                   // Zero terminate
1843
0
}
1844
1845
const char* ImStrSkipBlank(const char* str)
1846
0
{
1847
0
    while (str[0] == ' ' || str[0] == '\t')
1848
0
        str++;
1849
0
    return str;
1850
0
}
1851
1852
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1853
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1854
// B) When buf==NULL vsnprintf() will return the output size.
1855
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1856
1857
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1858
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1859
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1860
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1861
#ifdef IMGUI_USE_STB_SPRINTF
1862
#define STB_SPRINTF_IMPLEMENTATION
1863
#ifdef IMGUI_STB_SPRINTF_FILENAME
1864
#include IMGUI_STB_SPRINTF_FILENAME
1865
#else
1866
#include "stb_sprintf.h"
1867
#endif
1868
#endif
1869
1870
#if defined(_MSC_VER) && !defined(vsnprintf)
1871
#define vsnprintf _vsnprintf
1872
#endif
1873
1874
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1875
2.36k
{
1876
2.36k
    va_list args;
1877
2.36k
    va_start(args, fmt);
1878
#ifdef IMGUI_USE_STB_SPRINTF
1879
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1880
#else
1881
2.36k
    int w = vsnprintf(buf, buf_size, fmt, args);
1882
2.36k
#endif
1883
2.36k
    va_end(args);
1884
2.36k
    if (buf == NULL)
1885
0
        return w;
1886
2.36k
    if (w == -1 || w >= (int)buf_size)
1887
0
        w = (int)buf_size - 1;
1888
2.36k
    buf[w] = 0;
1889
2.36k
    return w;
1890
2.36k
}
1891
1892
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1893
105k
{
1894
#ifdef IMGUI_USE_STB_SPRINTF
1895
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1896
#else
1897
105k
    int w = vsnprintf(buf, buf_size, fmt, args);
1898
105k
#endif
1899
105k
    if (buf == NULL)
1900
0
        return w;
1901
105k
    if (w == -1 || w >= (int)buf_size)
1902
0
        w = (int)buf_size - 1;
1903
105k
    buf[w] = 0;
1904
105k
    return w;
1905
105k
}
1906
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1907
1908
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1909
103k
{
1910
103k
    ImGuiContext& g = *GImGui;
1911
103k
    va_list args;
1912
103k
    va_start(args, fmt);
1913
103k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1914
0
    {
1915
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1916
0
        *out_buf = buf;
1917
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1918
0
    }
1919
103k
    else
1920
103k
    {
1921
103k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1922
103k
        *out_buf = g.TempBuffer.Data;
1923
103k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1924
103k
    }
1925
103k
    va_end(args);
1926
103k
}
1927
1928
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
1929
4.72k
{
1930
4.72k
    ImGuiContext& g = *GImGui;
1931
4.72k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1932
2.36k
    {
1933
2.36k
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1934
2.36k
        *out_buf = buf;
1935
2.36k
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1936
2.36k
    }
1937
2.36k
    else
1938
2.36k
    {
1939
2.36k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1940
2.36k
        *out_buf = g.TempBuffer.Data;
1941
2.36k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1942
2.36k
    }
1943
4.72k
}
1944
1945
// CRC32 needs a 1KB lookup table (not cache friendly)
1946
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
1947
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
1948
static const ImU32 GCrc32LookupTable[256] =
1949
{
1950
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
1951
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
1952
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
1953
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
1954
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
1955
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
1956
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
1957
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
1958
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
1959
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
1960
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
1961
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
1962
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
1963
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
1964
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
1965
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
1966
};
1967
1968
// Known size hash
1969
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
1970
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1971
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
1972
103k
{
1973
103k
    ImU32 crc = ~seed;
1974
103k
    const unsigned char* data = (const unsigned char*)data_p;
1975
103k
    const ImU32* crc32_lut = GCrc32LookupTable;
1976
517k
    while (data_size-- != 0)
1977
413k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
1978
103k
    return ~crc;
1979
103k
}
1980
1981
// Zero-terminated string hash, with support for ### to reset back to seed value
1982
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
1983
// Because this syntax is rarely used we are optimizing for the common case.
1984
// - If we reach ### in the string we discard the hash so far and reset to the seed.
1985
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
1986
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1987
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
1988
1.27M
{
1989
1.27M
    seed = ~seed;
1990
1.27M
    ImU32 crc = seed;
1991
1.27M
    const unsigned char* data = (const unsigned char*)data_p;
1992
1.27M
    const ImU32* crc32_lut = GCrc32LookupTable;
1993
1.27M
    if (data_size != 0)
1994
0
    {
1995
0
        while (data_size-- != 0)
1996
0
        {
1997
0
            unsigned char c = *data++;
1998
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
1999
0
                crc = seed;
2000
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2001
0
        }
2002
0
    }
2003
1.27M
    else
2004
1.27M
    {
2005
18.1M
        while (unsigned char c = *data++)
2006
16.8M
        {
2007
16.8M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2008
167k
                crc = seed;
2009
16.8M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2010
16.8M
        }
2011
1.27M
    }
2012
1.27M
    return ~crc;
2013
1.27M
}
2014
2015
//-----------------------------------------------------------------------------
2016
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2017
//-----------------------------------------------------------------------------
2018
2019
// Default file functions
2020
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2021
2022
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2023
0
{
2024
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2025
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2026
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2027
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2028
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2029
    ImVector<wchar_t> buf;
2030
    buf.resize(filename_wsize + mode_wsize);
2031
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
2032
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
2033
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
2034
#else
2035
0
    return fopen(filename, mode);
2036
0
#endif
2037
0
}
2038
2039
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2040
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2041
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2042
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2043
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2044
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2045
2046
// Helper: Load file content into memory
2047
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2048
// This can't really be used with "rt" because fseek size won't match read size.
2049
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2050
0
{
2051
0
    IM_ASSERT(filename && mode);
2052
0
    if (out_file_size)
2053
0
        *out_file_size = 0;
2054
2055
0
    ImFileHandle f;
2056
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2057
0
        return NULL;
2058
2059
0
    size_t file_size = (size_t)ImFileGetSize(f);
2060
0
    if (file_size == (size_t)-1)
2061
0
    {
2062
0
        ImFileClose(f);
2063
0
        return NULL;
2064
0
    }
2065
2066
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2067
0
    if (file_data == NULL)
2068
0
    {
2069
0
        ImFileClose(f);
2070
0
        return NULL;
2071
0
    }
2072
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2073
0
    {
2074
0
        ImFileClose(f);
2075
0
        IM_FREE(file_data);
2076
0
        return NULL;
2077
0
    }
2078
0
    if (padding_bytes > 0)
2079
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2080
2081
0
    ImFileClose(f);
2082
0
    if (out_file_size)
2083
0
        *out_file_size = file_size;
2084
2085
0
    return file_data;
2086
0
}
2087
2088
//-----------------------------------------------------------------------------
2089
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2090
//-----------------------------------------------------------------------------
2091
2092
IM_MSVC_RUNTIME_CHECKS_OFF
2093
2094
// Convert UTF-8 to 32-bit character, process single character input.
2095
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2096
// We handle UTF-8 decoding error by skipping forward.
2097
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2098
54.7M
{
2099
54.7M
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2100
54.7M
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2101
54.7M
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2102
54.7M
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2103
54.7M
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2104
54.7M
    int len = lengths[*(const unsigned char*)in_text >> 3];
2105
54.7M
    int wanted = len + (len ? 0 : 1);
2106
2107
54.7M
    if (in_text_end == NULL)
2108
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2109
2110
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2111
    // so it is fast even with excessive branching.
2112
54.7M
    unsigned char s[4];
2113
54.7M
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2114
54.7M
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2115
54.7M
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2116
54.7M
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2117
2118
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2119
54.7M
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2120
54.7M
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2121
54.7M
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2122
54.7M
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2123
54.7M
    *out_char >>= shiftc[len];
2124
2125
    // Accumulate the various error conditions.
2126
54.7M
    int e = 0;
2127
54.7M
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2128
54.7M
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2129
54.7M
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2130
54.7M
    e |= (s[1] & 0xc0) >> 2;
2131
54.7M
    e |= (s[2] & 0xc0) >> 4;
2132
54.7M
    e |= (s[3]       ) >> 6;
2133
54.7M
    e ^= 0x2a; // top two bits of each tail byte correct?
2134
54.7M
    e >>= shifte[len];
2135
2136
54.7M
    if (e)
2137
798k
    {
2138
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2139
        // One byte is consumed in case of invalid first byte of in_text.
2140
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2141
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2142
798k
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2143
798k
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2144
798k
    }
2145
2146
54.7M
    return wanted;
2147
54.7M
}
2148
2149
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2150
0
{
2151
0
    ImWchar* buf_out = buf;
2152
0
    ImWchar* buf_end = buf + buf_size;
2153
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2154
0
    {
2155
0
        unsigned int c;
2156
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2157
0
        *buf_out++ = (ImWchar)c;
2158
0
    }
2159
0
    *buf_out = 0;
2160
0
    if (in_text_remaining)
2161
0
        *in_text_remaining = in_text;
2162
0
    return (int)(buf_out - buf);
2163
0
}
2164
2165
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2166
0
{
2167
0
    int char_count = 0;
2168
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2169
0
    {
2170
0
        unsigned int c;
2171
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2172
0
        char_count++;
2173
0
    }
2174
0
    return char_count;
2175
0
}
2176
2177
// Based on stb_to_utf8() from github.com/nothings/stb/
2178
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2179
0
{
2180
0
    if (c < 0x80)
2181
0
    {
2182
0
        buf[0] = (char)c;
2183
0
        return 1;
2184
0
    }
2185
0
    if (c < 0x800)
2186
0
    {
2187
0
        if (buf_size < 2) return 0;
2188
0
        buf[0] = (char)(0xc0 + (c >> 6));
2189
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2190
0
        return 2;
2191
0
    }
2192
0
    if (c < 0x10000)
2193
0
    {
2194
0
        if (buf_size < 3) return 0;
2195
0
        buf[0] = (char)(0xe0 + (c >> 12));
2196
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2197
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2198
0
        return 3;
2199
0
    }
2200
0
    if (c <= 0x10FFFF)
2201
0
    {
2202
0
        if (buf_size < 4) return 0;
2203
0
        buf[0] = (char)(0xf0 + (c >> 18));
2204
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2205
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2206
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2207
0
        return 4;
2208
0
    }
2209
    // Invalid code point, the max unicode is 0x10FFFF
2210
0
    return 0;
2211
0
}
2212
2213
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2214
0
{
2215
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2216
0
    out_buf[count] = 0;
2217
0
    return out_buf;
2218
0
}
2219
2220
// Not optimal but we very rarely use this function.
2221
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2222
0
{
2223
0
    unsigned int unused = 0;
2224
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2225
0
}
2226
2227
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2228
0
{
2229
0
    if (c < 0x80) return 1;
2230
0
    if (c < 0x800) return 2;
2231
0
    if (c < 0x10000) return 3;
2232
0
    if (c <= 0x10FFFF) return 4;
2233
0
    return 3;
2234
0
}
2235
2236
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2237
0
{
2238
0
    char* buf_p = out_buf;
2239
0
    const char* buf_end = out_buf + out_buf_size;
2240
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2241
0
    {
2242
0
        unsigned int c = (unsigned int)(*in_text++);
2243
0
        if (c < 0x80)
2244
0
            *buf_p++ = (char)c;
2245
0
        else
2246
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2247
0
    }
2248
0
    *buf_p = 0;
2249
0
    return (int)(buf_p - out_buf);
2250
0
}
2251
2252
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2253
0
{
2254
0
    int bytes_count = 0;
2255
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2256
0
    {
2257
0
        unsigned int c = (unsigned int)(*in_text++);
2258
0
        if (c < 0x80)
2259
0
            bytes_count++;
2260
0
        else
2261
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2262
0
    }
2263
0
    return bytes_count;
2264
0
}
2265
IM_MSVC_RUNTIME_CHECKS_RESTORE
2266
2267
//-----------------------------------------------------------------------------
2268
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2269
// Note: The Convert functions are early design which are not consistent with other API.
2270
//-----------------------------------------------------------------------------
2271
2272
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2273
0
{
2274
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2275
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2276
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2277
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2278
0
    return IM_COL32(r, g, b, 0xFF);
2279
0
}
2280
2281
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2282
507k
{
2283
507k
    float s = 1.0f / 255.0f;
2284
507k
    return ImVec4(
2285
507k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2286
507k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2287
507k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2288
507k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2289
507k
}
2290
2291
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2292
2.84M
{
2293
2.84M
    ImU32 out;
2294
2.84M
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2295
2.84M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2296
2.84M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2297
2.84M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2298
2.84M
    return out;
2299
2.84M
}
2300
2301
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2302
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2303
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2304
0
{
2305
0
    float K = 0.f;
2306
0
    if (g < b)
2307
0
    {
2308
0
        ImSwap(g, b);
2309
0
        K = -1.f;
2310
0
    }
2311
0
    if (r < g)
2312
0
    {
2313
0
        ImSwap(r, g);
2314
0
        K = -2.f / 6.f - K;
2315
0
    }
2316
2317
0
    const float chroma = r - (g < b ? g : b);
2318
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2319
0
    out_s = chroma / (r + 1e-20f);
2320
0
    out_v = r;
2321
0
}
2322
2323
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2324
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2325
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2326
0
{
2327
0
    if (s == 0.0f)
2328
0
    {
2329
        // gray
2330
0
        out_r = out_g = out_b = v;
2331
0
        return;
2332
0
    }
2333
2334
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2335
0
    int   i = (int)h;
2336
0
    float f = h - (float)i;
2337
0
    float p = v * (1.0f - s);
2338
0
    float q = v * (1.0f - s * f);
2339
0
    float t = v * (1.0f - s * (1.0f - f));
2340
2341
0
    switch (i)
2342
0
    {
2343
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2344
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2345
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2346
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2347
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2348
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2349
0
    }
2350
0
}
2351
2352
//-----------------------------------------------------------------------------
2353
// [SECTION] ImGuiStorage
2354
// Helper: Key->value storage
2355
//-----------------------------------------------------------------------------
2356
2357
// std::lower_bound but without the bullshit
2358
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2359
440k
{
2360
440k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2361
440k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2362
440k
    size_t count = (size_t)(last - first);
2363
1.44M
    while (count > 0)
2364
1.00M
    {
2365
1.00M
        size_t count2 = count >> 1;
2366
1.00M
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2367
1.00M
        if (mid->key < key)
2368
272k
        {
2369
272k
            first = ++mid;
2370
272k
            count -= count2 + 1;
2371
272k
        }
2372
736k
        else
2373
736k
        {
2374
736k
            count = count2;
2375
736k
        }
2376
1.00M
    }
2377
440k
    return first;
2378
440k
}
2379
2380
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2381
void ImGuiStorage::BuildSortByKey()
2382
0
{
2383
0
    struct StaticFunc
2384
0
    {
2385
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2386
0
        {
2387
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2388
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2389
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2390
0
            return 0;
2391
0
        }
2392
0
    };
2393
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2394
0
}
2395
2396
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2397
0
{
2398
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2399
0
    if (it == Data.end() || it->key != key)
2400
0
        return default_val;
2401
0
    return it->val_i;
2402
0
}
2403
2404
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2405
0
{
2406
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2407
0
}
2408
2409
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2410
0
{
2411
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2412
0
    if (it == Data.end() || it->key != key)
2413
0
        return default_val;
2414
0
    return it->val_f;
2415
0
}
2416
2417
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2418
440k
{
2419
440k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2420
440k
    if (it == Data.end() || it->key != key)
2421
10
        return NULL;
2422
440k
    return it->val_p;
2423
440k
}
2424
2425
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2426
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2427
0
{
2428
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2429
0
    if (it == Data.end() || it->key != key)
2430
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2431
0
    return &it->val_i;
2432
0
}
2433
2434
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2435
0
{
2436
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2437
0
}
2438
2439
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2440
0
{
2441
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2442
0
    if (it == Data.end() || it->key != key)
2443
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2444
0
    return &it->val_f;
2445
0
}
2446
2447
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2448
0
{
2449
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2450
0
    if (it == Data.end() || it->key != key)
2451
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2452
0
    return &it->val_p;
2453
0
}
2454
2455
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2456
void ImGuiStorage::SetInt(ImGuiID key, int val)
2457
0
{
2458
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2459
0
    if (it == Data.end() || it->key != key)
2460
0
    {
2461
0
        Data.insert(it, ImGuiStoragePair(key, val));
2462
0
        return;
2463
0
    }
2464
0
    it->val_i = val;
2465
0
}
2466
2467
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2468
0
{
2469
0
    SetInt(key, val ? 1 : 0);
2470
0
}
2471
2472
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2473
0
{
2474
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2475
0
    if (it == Data.end() || it->key != key)
2476
0
    {
2477
0
        Data.insert(it, ImGuiStoragePair(key, val));
2478
0
        return;
2479
0
    }
2480
0
    it->val_f = val;
2481
0
}
2482
2483
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2484
10
{
2485
10
    ImGuiStoragePair* it = LowerBound(Data, key);
2486
10
    if (it == Data.end() || it->key != key)
2487
10
    {
2488
10
        Data.insert(it, ImGuiStoragePair(key, val));
2489
10
        return;
2490
10
    }
2491
0
    it->val_p = val;
2492
0
}
2493
2494
void ImGuiStorage::SetAllInt(int v)
2495
0
{
2496
0
    for (int i = 0; i < Data.Size; i++)
2497
0
        Data[i].val_i = v;
2498
0
}
2499
2500
//-----------------------------------------------------------------------------
2501
// [SECTION] ImGuiTextFilter
2502
//-----------------------------------------------------------------------------
2503
2504
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2505
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2506
0
{
2507
0
    InputBuf[0] = 0;
2508
0
    CountGrep = 0;
2509
0
    if (default_filter)
2510
0
    {
2511
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2512
0
        Build();
2513
0
    }
2514
0
}
2515
2516
bool ImGuiTextFilter::Draw(const char* label, float width)
2517
0
{
2518
0
    if (width != 0.0f)
2519
0
        ImGui::SetNextItemWidth(width);
2520
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2521
0
    if (value_changed)
2522
0
        Build();
2523
0
    return value_changed;
2524
0
}
2525
2526
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2527
0
{
2528
0
    out->resize(0);
2529
0
    const char* wb = b;
2530
0
    const char* we = wb;
2531
0
    while (we < e)
2532
0
    {
2533
0
        if (*we == separator)
2534
0
        {
2535
0
            out->push_back(ImGuiTextRange(wb, we));
2536
0
            wb = we + 1;
2537
0
        }
2538
0
        we++;
2539
0
    }
2540
0
    if (wb != we)
2541
0
        out->push_back(ImGuiTextRange(wb, we));
2542
0
}
2543
2544
void ImGuiTextFilter::Build()
2545
0
{
2546
0
    Filters.resize(0);
2547
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2548
0
    input_range.split(',', &Filters);
2549
2550
0
    CountGrep = 0;
2551
0
    for (int i = 0; i != Filters.Size; i++)
2552
0
    {
2553
0
        ImGuiTextRange& f = Filters[i];
2554
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2555
0
            f.b++;
2556
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2557
0
            f.e--;
2558
0
        if (f.empty())
2559
0
            continue;
2560
0
        if (Filters[i].b[0] != '-')
2561
0
            CountGrep += 1;
2562
0
    }
2563
0
}
2564
2565
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2566
0
{
2567
0
    if (Filters.empty())
2568
0
        return true;
2569
2570
0
    if (text == NULL)
2571
0
        text = "";
2572
2573
0
    for (int i = 0; i != Filters.Size; i++)
2574
0
    {
2575
0
        const ImGuiTextRange& f = Filters[i];
2576
0
        if (f.empty())
2577
0
            continue;
2578
0
        if (f.b[0] == '-')
2579
0
        {
2580
            // Subtract
2581
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2582
0
                return false;
2583
0
        }
2584
0
        else
2585
0
        {
2586
            // Grep
2587
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2588
0
                return true;
2589
0
        }
2590
0
    }
2591
2592
    // Implicit * grep
2593
0
    if (CountGrep == 0)
2594
0
        return true;
2595
2596
0
    return false;
2597
0
}
2598
2599
//-----------------------------------------------------------------------------
2600
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2601
//-----------------------------------------------------------------------------
2602
2603
// On some platform vsnprintf() takes va_list by reference and modifies it.
2604
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2605
#ifndef va_copy
2606
#if defined(__GNUC__) || defined(__clang__)
2607
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2608
#else
2609
#define va_copy(dest, src) (dest = src)
2610
#endif
2611
#endif
2612
2613
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2614
2615
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2616
0
{
2617
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2618
2619
    // Add zero-terminator the first time
2620
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2621
0
    const int needed_sz = write_off + len;
2622
0
    if (write_off + len >= Buf.Capacity)
2623
0
    {
2624
0
        int new_capacity = Buf.Capacity * 2;
2625
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2626
0
    }
2627
2628
0
    Buf.resize(needed_sz);
2629
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2630
0
    Buf[write_off - 1 + len] = 0;
2631
0
}
2632
2633
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2634
0
{
2635
0
    va_list args;
2636
0
    va_start(args, fmt);
2637
0
    appendfv(fmt, args);
2638
0
    va_end(args);
2639
0
}
2640
2641
// Helper: Text buffer for logging/accumulating text
2642
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2643
0
{
2644
0
    va_list args_copy;
2645
0
    va_copy(args_copy, args);
2646
2647
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2648
0
    if (len <= 0)
2649
0
    {
2650
0
        va_end(args_copy);
2651
0
        return;
2652
0
    }
2653
2654
    // Add zero-terminator the first time
2655
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2656
0
    const int needed_sz = write_off + len;
2657
0
    if (write_off + len >= Buf.Capacity)
2658
0
    {
2659
0
        int new_capacity = Buf.Capacity * 2;
2660
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2661
0
    }
2662
2663
0
    Buf.resize(needed_sz);
2664
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2665
0
    va_end(args_copy);
2666
0
}
2667
2668
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2669
0
{
2670
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2671
0
    if (old_size == new_size)
2672
0
        return;
2673
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2674
0
        LineOffsets.push_back(EndOffset);
2675
0
    const char* base_end = base + new_size;
2676
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2677
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2678
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2679
0
    EndOffset = ImMax(EndOffset, new_size);
2680
0
}
2681
2682
//-----------------------------------------------------------------------------
2683
// [SECTION] ImGuiListClipper
2684
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
2685
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
2686
//-----------------------------------------------------------------------------
2687
2688
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2689
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2690
static bool GetSkipItemForListClipping()
2691
0
{
2692
0
    ImGuiContext& g = *GImGui;
2693
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2694
0
}
2695
2696
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2697
// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2698
// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2699
// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2700
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2701
{
2702
    ImGuiContext& g = *GImGui;
2703
    ImGuiWindow* window = g.CurrentWindow;
2704
    if (g.LogEnabled)
2705
    {
2706
        // If logging is active, do not perform any clipping
2707
        *out_items_display_start = 0;
2708
        *out_items_display_end = items_count;
2709
        return;
2710
    }
2711
    if (GetSkipItemForListClipping())
2712
    {
2713
        *out_items_display_start = *out_items_display_end = 0;
2714
        return;
2715
    }
2716
2717
    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2718
    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2719
    ImRect rect = window->ClipRect;
2720
    if (g.NavMoveScoringItems)
2721
        rect.Add(g.NavScoringNoClipRect);
2722
    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2723
        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2724
2725
    const ImVec2 pos = window->DC.CursorPos;
2726
    int start = (int)((rect.Min.y - pos.y) / items_height);
2727
    int end = (int)((rect.Max.y - pos.y) / items_height);
2728
2729
    // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2730
    // FIXME: Verify this works with tabbing
2731
    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2732
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2733
        start--;
2734
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2735
        end++;
2736
2737
    start = ImClamp(start, 0, items_count);
2738
    end = ImClamp(end + 1, start, items_count);
2739
    *out_items_display_start = start;
2740
    *out_items_display_end = end;
2741
}
2742
#endif
2743
2744
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2745
0
{
2746
0
    if (ranges.Size - offset <= 1)
2747
0
        return;
2748
2749
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2750
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2751
0
        for (int i = offset; i < sort_end + offset; ++i)
2752
0
            if (ranges[i].Min > ranges[i + 1].Min)
2753
0
                ImSwap(ranges[i], ranges[i + 1]);
2754
2755
    // Now fuse ranges together as much as possible.
2756
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2757
0
    {
2758
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2759
0
        if (ranges[i - 1].Max < ranges[i].Min)
2760
0
            continue;
2761
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2762
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2763
0
        ranges.erase(ranges.Data + i);
2764
0
        i--;
2765
0
    }
2766
0
}
2767
2768
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2769
0
{
2770
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2771
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2772
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2773
0
    ImGuiContext& g = *GImGui;
2774
0
    ImGuiWindow* window = g.CurrentWindow;
2775
0
    float off_y = pos_y - window->DC.CursorPos.y;
2776
0
    window->DC.CursorPos.y = pos_y;
2777
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2778
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2779
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2780
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2781
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2782
0
    if (ImGuiTable* table = g.CurrentTable)
2783
0
    {
2784
0
        if (table->IsInsideRow)
2785
0
            ImGui::TableEndRow(table);
2786
0
        table->RowPosY2 = window->DC.CursorPos.y;
2787
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2788
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2789
0
        table->RowBgColorCounter += row_increase;
2790
0
    }
2791
0
}
2792
2793
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2794
0
{
2795
    // StartPosY starts from ItemsFrozen hence the subtraction
2796
    // Perform the add and multiply with double to allow seeking through larger ranges
2797
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2798
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2799
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2800
0
}
2801
2802
ImGuiListClipper::ImGuiListClipper()
2803
0
{
2804
0
    memset(this, 0, sizeof(*this));
2805
0
    Ctx = ImGui::GetCurrentContext();
2806
0
    IM_ASSERT(Ctx != NULL);
2807
0
    ItemsCount = -1;
2808
0
}
2809
2810
ImGuiListClipper::~ImGuiListClipper()
2811
0
{
2812
0
    End();
2813
0
}
2814
2815
void ImGuiListClipper::Begin(int items_count, float items_height)
2816
0
{
2817
0
    ImGuiContext& g = *Ctx;
2818
0
    ImGuiWindow* window = g.CurrentWindow;
2819
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2820
2821
0
    if (ImGuiTable* table = g.CurrentTable)
2822
0
        if (table->IsInsideRow)
2823
0
            ImGui::TableEndRow(table);
2824
2825
0
    StartPosY = window->DC.CursorPos.y;
2826
0
    ItemsHeight = items_height;
2827
0
    ItemsCount = items_count;
2828
0
    DisplayStart = -1;
2829
0
    DisplayEnd = 0;
2830
2831
    // Acquire temporary buffer
2832
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2833
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2834
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2835
0
    data->Reset(this);
2836
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2837
0
    TempData = data;
2838
0
}
2839
2840
void ImGuiListClipper::End()
2841
0
{
2842
0
    ImGuiContext& g = *Ctx;
2843
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2844
0
    {
2845
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2846
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2847
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2848
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2849
2850
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2851
0
        IM_ASSERT(data->ListClipper == this);
2852
0
        data->StepNo = data->Ranges.Size;
2853
0
        if (--g.ClipperTempDataStacked > 0)
2854
0
        {
2855
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2856
0
            data->ListClipper->TempData = data;
2857
0
        }
2858
0
        TempData = NULL;
2859
0
    }
2860
0
    ItemsCount = -1;
2861
0
}
2862
2863
void ImGuiListClipper::ForceDisplayRangeByIndices(int item_min, int item_max)
2864
0
{
2865
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2866
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2867
0
    IM_ASSERT(item_min <= item_max);
2868
0
    if (item_min < item_max)
2869
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_min, item_max));
2870
0
}
2871
2872
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2873
0
{
2874
0
    ImGuiContext& g = *clipper->Ctx;
2875
0
    ImGuiWindow* window = g.CurrentWindow;
2876
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2877
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2878
2879
0
    ImGuiTable* table = g.CurrentTable;
2880
0
    if (table && table->IsInsideRow)
2881
0
        ImGui::TableEndRow(table);
2882
2883
    // No items
2884
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2885
0
        return false;
2886
2887
    // While we are in frozen row state, keep displaying items one by one, unclipped
2888
    // FIXME: Could be stored as a table-agnostic state.
2889
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2890
0
    {
2891
0
        clipper->DisplayStart = data->ItemsFrozen;
2892
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2893
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2894
0
            data->ItemsFrozen++;
2895
0
        return true;
2896
0
    }
2897
2898
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2899
0
    bool calc_clipping = false;
2900
0
    if (data->StepNo == 0)
2901
0
    {
2902
0
        clipper->StartPosY = window->DC.CursorPos.y;
2903
0
        if (clipper->ItemsHeight <= 0.0f)
2904
0
        {
2905
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2906
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2907
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2908
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2909
0
            data->StepNo = 1;
2910
0
            return true;
2911
0
        }
2912
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2913
0
    }
2914
2915
    // Step 1: Let the clipper infer height from first range
2916
0
    if (clipper->ItemsHeight <= 0.0f)
2917
0
    {
2918
0
        IM_ASSERT(data->StepNo == 1);
2919
0
        if (table)
2920
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2921
2922
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2923
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2924
0
        if (affected_by_floating_point_precision)
2925
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2926
2927
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2928
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
2929
0
    }
2930
2931
    // Step 0 or 1: Calculate the actual ranges of visible elements.
2932
0
    const int already_submitted = clipper->DisplayEnd;
2933
0
    if (calc_clipping)
2934
0
    {
2935
0
        if (g.LogEnabled)
2936
0
        {
2937
            // If logging is active, do not perform any clipping
2938
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
2939
0
        }
2940
0
        else
2941
0
        {
2942
            // Add range selected to be included for navigation
2943
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2944
0
            if (is_nav_request)
2945
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
2946
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1)
2947
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
2948
2949
            // Add focused/active item
2950
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
2951
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
2952
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
2953
2954
            // Add visible range
2955
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
2956
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
2957
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
2958
0
        }
2959
2960
        // Convert position ranges to item index ranges
2961
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
2962
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
2963
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
2964
0
        for (int i = 0; i < data->Ranges.Size; i++)
2965
0
            if (data->Ranges[i].PosToIndexConvert)
2966
0
            {
2967
0
                int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
2968
0
                int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
2969
0
                data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
2970
0
                data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, clipper->ItemsCount);
2971
0
                data->Ranges[i].PosToIndexConvert = false;
2972
0
            }
2973
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
2974
0
    }
2975
2976
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
2977
0
    if (data->StepNo < data->Ranges.Size)
2978
0
    {
2979
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
2980
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
2981
0
        if (clipper->DisplayStart > already_submitted) //-V1051
2982
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
2983
0
        data->StepNo++;
2984
0
        return true;
2985
0
    }
2986
2987
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
2988
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
2989
0
    if (clipper->ItemsCount < INT_MAX)
2990
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
2991
2992
0
    return false;
2993
0
}
2994
2995
bool ImGuiListClipper::Step()
2996
0
{
2997
0
    ImGuiContext& g = *Ctx;
2998
0
    bool need_items_height = (ItemsHeight <= 0.0f);
2999
0
    bool ret = ImGuiListClipper_StepInternal(this);
3000
0
    if (ret && (DisplayStart == DisplayEnd))
3001
0
        ret = false;
3002
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3003
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3004
0
    if (need_items_height && ItemsHeight > 0.0f)
3005
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3006
0
    if (ret)
3007
0
    {
3008
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3009
0
    }
3010
0
    else
3011
0
    {
3012
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3013
0
        End();
3014
0
    }
3015
0
    return ret;
3016
0
}
3017
3018
//-----------------------------------------------------------------------------
3019
// [SECTION] STYLING
3020
//-----------------------------------------------------------------------------
3021
3022
ImGuiStyle& ImGui::GetStyle()
3023
340k
{
3024
340k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3025
340k
    return GImGui->Style;
3026
340k
}
3027
3028
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3029
2.50M
{
3030
2.50M
    ImGuiStyle& style = GImGui->Style;
3031
2.50M
    ImVec4 c = style.Colors[idx];
3032
2.50M
    c.w *= style.Alpha * alpha_mul;
3033
2.50M
    return ColorConvertFloat4ToU32(c);
3034
2.50M
}
3035
3036
ImU32 ImGui::GetColorU32(const ImVec4& col)
3037
0
{
3038
0
    ImGuiStyle& style = GImGui->Style;
3039
0
    ImVec4 c = col;
3040
0
    c.w *= style.Alpha;
3041
0
    return ColorConvertFloat4ToU32(c);
3042
0
}
3043
3044
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3045
0
{
3046
0
    ImGuiStyle& style = GImGui->Style;
3047
0
    return style.Colors[idx];
3048
0
}
3049
3050
ImU32 ImGui::GetColorU32(ImU32 col)
3051
0
{
3052
0
    ImGuiStyle& style = GImGui->Style;
3053
0
    if (style.Alpha >= 1.0f)
3054
0
        return col;
3055
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3056
0
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
3057
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3058
0
}
3059
3060
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3061
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3062
0
{
3063
0
    ImGuiContext& g = *GImGui;
3064
0
    ImGuiColorMod backup;
3065
0
    backup.Col = idx;
3066
0
    backup.BackupValue = g.Style.Colors[idx];
3067
0
    g.ColorStack.push_back(backup);
3068
0
    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3069
0
}
3070
3071
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3072
171k
{
3073
171k
    ImGuiContext& g = *GImGui;
3074
171k
    ImGuiColorMod backup;
3075
171k
    backup.Col = idx;
3076
171k
    backup.BackupValue = g.Style.Colors[idx];
3077
171k
    g.ColorStack.push_back(backup);
3078
171k
    g.Style.Colors[idx] = col;
3079
171k
}
3080
3081
void ImGui::PopStyleColor(int count)
3082
171k
{
3083
171k
    ImGuiContext& g = *GImGui;
3084
171k
    if (g.ColorStack.Size < count)
3085
0
    {
3086
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3087
0
        count = g.ColorStack.Size;
3088
0
    }
3089
343k
    while (count > 0)
3090
171k
    {
3091
171k
        ImGuiColorMod& backup = g.ColorStack.back();
3092
171k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3093
171k
        g.ColorStack.pop_back();
3094
171k
        count--;
3095
171k
    }
3096
171k
}
3097
3098
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3099
{
3100
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3101
};
3102
3103
static const ImGuiDataVarInfo GStyleVarInfo[] =
3104
{
3105
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha
3106
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha
3107
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding
3108
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding
3109
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize
3110
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize
3111
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign
3112
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding
3113
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize
3114
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding
3115
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize
3116
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding
3117
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding
3118
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize
3119
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing
3120
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing
3121
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing
3122
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding
3123
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize
3124
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding
3125
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize
3126
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding
3127
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding
3128
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign
3129
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3130
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3131
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextAlign) },     // ImGuiStyleVar_SeparatorTextAlign
3132
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextPadding) },   // ImGuiStyleVar_SeparatorTextPadding
3133
};
3134
3135
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3136
334k
{
3137
334k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3138
334k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3139
334k
    return &GStyleVarInfo[idx];
3140
334k
}
3141
3142
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3143
0
{
3144
0
    ImGuiContext& g = *GImGui;
3145
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3146
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3147
0
    {
3148
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3149
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3150
0
        *pvar = val;
3151
0
        return;
3152
0
    }
3153
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3154
0
}
3155
3156
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3157
167k
{
3158
167k
    ImGuiContext& g = *GImGui;
3159
167k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3160
167k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3161
167k
    {
3162
167k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3163
167k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3164
167k
        *pvar = val;
3165
167k
        return;
3166
167k
    }
3167
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3168
0
}
3169
3170
void ImGui::PopStyleVar(int count)
3171
167k
{
3172
167k
    ImGuiContext& g = *GImGui;
3173
167k
    if (g.StyleVarStack.Size < count)
3174
0
    {
3175
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3176
0
        count = g.StyleVarStack.Size;
3177
0
    }
3178
334k
    while (count > 0)
3179
167k
    {
3180
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3181
167k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3182
167k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3183
167k
        void* data = info->GetVarPtr(&g.Style);
3184
167k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3185
167k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3186
167k
        g.StyleVarStack.pop_back();
3187
167k
        count--;
3188
167k
    }
3189
167k
}
3190
3191
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3192
0
{
3193
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3194
0
    switch (idx)
3195
0
    {
3196
0
    case ImGuiCol_Text: return "Text";
3197
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3198
0
    case ImGuiCol_WindowBg: return "WindowBg";
3199
0
    case ImGuiCol_ChildBg: return "ChildBg";
3200
0
    case ImGuiCol_PopupBg: return "PopupBg";
3201
0
    case ImGuiCol_Border: return "Border";
3202
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3203
0
    case ImGuiCol_FrameBg: return "FrameBg";
3204
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3205
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3206
0
    case ImGuiCol_TitleBg: return "TitleBg";
3207
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3208
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3209
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3210
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3211
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3212
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3213
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3214
0
    case ImGuiCol_CheckMark: return "CheckMark";
3215
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3216
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3217
0
    case ImGuiCol_Button: return "Button";
3218
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3219
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3220
0
    case ImGuiCol_Header: return "Header";
3221
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3222
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3223
0
    case ImGuiCol_Separator: return "Separator";
3224
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3225
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3226
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3227
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3228
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3229
0
    case ImGuiCol_Tab: return "Tab";
3230
0
    case ImGuiCol_TabHovered: return "TabHovered";
3231
0
    case ImGuiCol_TabActive: return "TabActive";
3232
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3233
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3234
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3235
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3236
0
    case ImGuiCol_PlotLines: return "PlotLines";
3237
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3238
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3239
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3240
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3241
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3242
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3243
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3244
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3245
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3246
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3247
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3248
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3249
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3250
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3251
0
    }
3252
0
    IM_ASSERT(0);
3253
0
    return "Unknown";
3254
0
}
3255
3256
3257
//-----------------------------------------------------------------------------
3258
// [SECTION] RENDER HELPERS
3259
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3260
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3261
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3262
//-----------------------------------------------------------------------------
3263
3264
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3265
668k
{
3266
668k
    const char* text_display_end = text;
3267
668k
    if (!text_end)
3268
668k
        text_end = (const char*)-1;
3269
3270
6.01M
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3271
5.34M
        text_display_end++;
3272
668k
    return text_display_end;
3273
668k
}
3274
3275
// Internal ImGui functions to render text
3276
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3277
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3278
1.21k
{
3279
1.21k
    ImGuiContext& g = *GImGui;
3280
1.21k
    ImGuiWindow* window = g.CurrentWindow;
3281
3282
    // Hide anything after a '##' string
3283
1.21k
    const char* text_display_end;
3284
1.21k
    if (hide_text_after_hash)
3285
0
    {
3286
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3287
0
    }
3288
1.21k
    else
3289
1.21k
    {
3290
1.21k
        if (!text_end)
3291
0
            text_end = text + strlen(text); // FIXME-OPT
3292
1.21k
        text_display_end = text_end;
3293
1.21k
    }
3294
3295
1.21k
    if (text != text_display_end)
3296
1.21k
    {
3297
1.21k
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3298
1.21k
        if (g.LogEnabled)
3299
0
            LogRenderedText(&pos, text, text_display_end);
3300
1.21k
    }
3301
1.21k
}
3302
3303
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3304
2.73k
{
3305
2.73k
    ImGuiContext& g = *GImGui;
3306
2.73k
    ImGuiWindow* window = g.CurrentWindow;
3307
3308
2.73k
    if (!text_end)
3309
0
        text_end = text + strlen(text); // FIXME-OPT
3310
3311
2.73k
    if (text != text_end)
3312
2.72k
    {
3313
2.72k
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3314
2.72k
        if (g.LogEnabled)
3315
0
            LogRenderedText(&pos, text, text_end);
3316
2.72k
    }
3317
2.73k
}
3318
3319
// Default clip_rect uses (pos_min,pos_max)
3320
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3321
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3322
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3323
// better advantage of the render function taking size into account for coarse clipping.
3324
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3325
334k
{
3326
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3327
334k
    ImVec2 pos = pos_min;
3328
334k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3329
3330
334k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3331
334k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3332
334k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3333
334k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3334
334k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3335
3336
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3337
334k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3338
334k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3339
3340
    // Render
3341
334k
    if (need_clipping)
3342
102k
    {
3343
102k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3344
102k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3345
102k
    }
3346
232k
    else
3347
232k
    {
3348
232k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3349
232k
    }
3350
334k
}
3351
3352
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3353
334k
{
3354
    // Hide anything after a '##' string
3355
334k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3356
334k
    const int text_len = (int)(text_display_end - text);
3357
334k
    if (text_len == 0)
3358
0
        return;
3359
3360
334k
    ImGuiContext& g = *GImGui;
3361
334k
    ImGuiWindow* window = g.CurrentWindow;
3362
334k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3363
334k
    if (g.LogEnabled)
3364
0
        LogRenderedText(&pos_min, text, text_display_end);
3365
334k
}
3366
3367
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3368
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3369
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3370
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3371
0
{
3372
0
    ImGuiContext& g = *GImGui;
3373
0
    if (text_end_full == NULL)
3374
0
        text_end_full = FindRenderedTextEnd(text);
3375
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3376
3377
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3378
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3379
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3380
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3381
0
    if (text_size.x > pos_max.x - pos_min.x)
3382
0
    {
3383
        // Hello wo...
3384
        // |       |   |
3385
        // min   max   ellipsis_max
3386
        //          <-> this is generally some padding value
3387
3388
0
        const ImFont* font = draw_list->_Data->Font;
3389
0
        const float font_size = draw_list->_Data->FontSize;
3390
0
        const float font_scale = font_size / font->FontSize;
3391
0
        const char* text_end_ellipsis = NULL;
3392
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3393
3394
        // We can now claim the space between pos_max.x and ellipsis_max.x
3395
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3396
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3397
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3398
0
        {
3399
            // Always display at least 1 character if there's no room for character + ellipsis
3400
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3401
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3402
0
        }
3403
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3404
0
        {
3405
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3406
0
            text_end_ellipsis--;
3407
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3408
0
        }
3409
3410
        // Render text, render ellipsis
3411
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3412
0
        ImVec2 ellipsis_pos = ImFloor(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3413
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3414
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3415
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3416
0
    }
3417
0
    else
3418
0
    {
3419
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3420
0
    }
3421
3422
0
    if (g.LogEnabled)
3423
0
        LogRenderedText(&pos_min, text, text_end_full);
3424
0
}
3425
3426
// Render a rectangle shaped with optional rounding and borders
3427
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3428
63.6k
{
3429
63.6k
    ImGuiContext& g = *GImGui;
3430
63.6k
    ImGuiWindow* window = g.CurrentWindow;
3431
63.6k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3432
63.6k
    const float border_size = g.Style.FrameBorderSize;
3433
63.6k
    if (border && border_size > 0.0f)
3434
63.6k
    {
3435
63.6k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3436
63.6k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3437
63.6k
    }
3438
63.6k
}
3439
3440
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3441
0
{
3442
0
    ImGuiContext& g = *GImGui;
3443
0
    ImGuiWindow* window = g.CurrentWindow;
3444
0
    const float border_size = g.Style.FrameBorderSize;
3445
0
    if (border_size > 0.0f)
3446
0
    {
3447
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3448
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3449
0
    }
3450
0
}
3451
3452
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3453
23.6k
{
3454
23.6k
    ImGuiContext& g = *GImGui;
3455
23.6k
    if (id != g.NavId)
3456
12.7k
        return;
3457
10.8k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3458
2.30k
        return;
3459
8.50k
    ImGuiWindow* window = g.CurrentWindow;
3460
8.50k
    if (window->DC.NavHideHighlightOneFrame)
3461
0
        return;
3462
3463
8.50k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3464
8.50k
    ImRect display_rect = bb;
3465
8.50k
    display_rect.ClipWith(window->ClipRect);
3466
8.50k
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3467
434
    {
3468
434
        const float THICKNESS = 2.0f;
3469
434
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3470
434
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3471
434
        bool fully_visible = window->ClipRect.Contains(display_rect);
3472
434
        if (!fully_visible)
3473
391
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3474
434
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3475
434
        if (!fully_visible)
3476
391
            window->DrawList->PopClipRect();
3477
434
    }
3478
8.50k
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3479
8.07k
    {
3480
8.07k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3481
8.07k
    }
3482
8.50k
}
3483
3484
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3485
0
{
3486
0
    ImGuiContext& g = *GImGui;
3487
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3488
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3489
0
    for (int n = 0; n < g.Viewports.Size; n++)
3490
0
    {
3491
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3492
0
        ImVec2 offset, size, uv[4];
3493
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3494
0
            continue;
3495
0
        ImGuiViewportP* viewport = g.Viewports[n];
3496
0
        const ImVec2 pos = base_pos - offset;
3497
0
        const float scale = base_scale * viewport->DpiScale;
3498
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3499
0
            continue;
3500
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3501
0
        ImTextureID tex_id = font_atlas->TexID;
3502
0
        draw_list->PushTextureID(tex_id);
3503
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3504
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3505
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3506
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3507
0
        draw_list->PopTextureID();
3508
0
    }
3509
0
}
3510
3511
//-----------------------------------------------------------------------------
3512
// [SECTION] INITIALIZATION, SHUTDOWN
3513
//-----------------------------------------------------------------------------
3514
3515
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3516
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3517
ImGuiContext* ImGui::GetCurrentContext()
3518
3
{
3519
3
    return GImGui;
3520
3
}
3521
3522
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3523
3
{
3524
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3525
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3526
#else
3527
3
    GImGui = ctx;
3528
3
#endif
3529
3
}
3530
3531
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3532
0
{
3533
0
    GImAllocatorAllocFunc = alloc_func;
3534
0
    GImAllocatorFreeFunc = free_func;
3535
0
    GImAllocatorUserData = user_data;
3536
0
}
3537
3538
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3539
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3540
0
{
3541
0
    *p_alloc_func = GImAllocatorAllocFunc;
3542
0
    *p_free_func = GImAllocatorFreeFunc;
3543
0
    *p_user_data = GImAllocatorUserData;
3544
0
}
3545
3546
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3547
3
{
3548
3
    ImGuiContext* prev_ctx = GetCurrentContext();
3549
3
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3550
3
    SetCurrentContext(ctx);
3551
3
    Initialize();
3552
3
    if (prev_ctx != NULL)
3553
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3554
3
    return ctx;
3555
3
}
3556
3557
void ImGui::DestroyContext(ImGuiContext* ctx)
3558
0
{
3559
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3560
0
    if (ctx == NULL) //-V1051
3561
0
        ctx = prev_ctx;
3562
0
    SetCurrentContext(ctx);
3563
0
    Shutdown();
3564
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3565
0
    IM_DELETE(ctx);
3566
0
}
3567
3568
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3569
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3570
{
3571
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3572
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3573
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3574
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3575
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3576
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3577
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3578
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3579
};
3580
3581
void ImGui::Initialize()
3582
3
{
3583
3
    ImGuiContext& g = *GImGui;
3584
3
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3585
3586
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3587
3
    {
3588
3
        ImGuiSettingsHandler ini_handler;
3589
3
        ini_handler.TypeName = "Window";
3590
3
        ini_handler.TypeHash = ImHashStr("Window");
3591
3
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3592
3
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3593
3
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3594
3
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3595
3
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3596
3
        AddSettingsHandler(&ini_handler);
3597
3
    }
3598
3
    TableSettingsAddSettingsHandler();
3599
3600
    // Setup default localization table
3601
3
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3602
3603
    // Setup default platform clipboard/IME handlers.
3604
3
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3605
3
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3606
3
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3607
3
    g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3608
3609
    // Create default viewport
3610
3
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3611
3
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3612
3
    viewport->Idx = 0;
3613
3
    viewport->PlatformWindowCreated = true;
3614
3
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3615
3
    g.Viewports.push_back(viewport);
3616
3
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3617
3
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3618
3619
3
#ifdef IMGUI_HAS_DOCK
3620
    // Initialize Docking
3621
3
    DockContextInitialize(&g);
3622
3
#endif
3623
3624
3
    g.Initialized = true;
3625
3
}
3626
3627
// This function is merely here to free heap allocations.
3628
void ImGui::Shutdown()
3629
0
{
3630
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3631
0
    ImGuiContext& g = *GImGui;
3632
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3633
0
    {
3634
0
        g.IO.Fonts->Locked = false;
3635
0
        IM_DELETE(g.IO.Fonts);
3636
0
    }
3637
0
    g.IO.Fonts = NULL;
3638
0
    g.DrawListSharedData.TempBuffer.clear();
3639
3640
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3641
0
    if (!g.Initialized)
3642
0
        return;
3643
3644
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3645
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3646
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3647
3648
    // Destroy platform windows
3649
0
    DestroyPlatformWindows();
3650
3651
    // Shutdown extensions
3652
0
    DockContextShutdown(&g);
3653
3654
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3655
3656
    // Clear everything else
3657
0
    g.Windows.clear_delete();
3658
0
    g.WindowsFocusOrder.clear();
3659
0
    g.WindowsTempSortBuffer.clear();
3660
0
    g.CurrentWindow = NULL;
3661
0
    g.CurrentWindowStack.clear();
3662
0
    g.WindowsById.Clear();
3663
0
    g.NavWindow = NULL;
3664
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3665
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3666
0
    g.MovingWindow = NULL;
3667
3668
0
    g.KeysRoutingTable.Clear();
3669
3670
0
    g.ColorStack.clear();
3671
0
    g.StyleVarStack.clear();
3672
0
    g.FontStack.clear();
3673
0
    g.OpenPopupStack.clear();
3674
0
    g.BeginPopupStack.clear();
3675
3676
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3677
0
    g.Viewports.clear_delete();
3678
3679
0
    g.TabBars.Clear();
3680
0
    g.CurrentTabBarStack.clear();
3681
0
    g.ShrinkWidthBuffer.clear();
3682
3683
0
    g.ClipperTempData.clear_destruct();
3684
3685
0
    g.Tables.Clear();
3686
0
    g.TablesTempData.clear_destruct();
3687
0
    g.DrawChannelsTempMergeBuffer.clear();
3688
3689
0
    g.ClipboardHandlerData.clear();
3690
0
    g.MenusIdSubmittedThisFrame.clear();
3691
0
    g.InputTextState.ClearFreeMemory();
3692
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3693
3694
0
    g.SettingsWindows.clear();
3695
0
    g.SettingsHandlers.clear();
3696
3697
0
    if (g.LogFile)
3698
0
    {
3699
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3700
0
        if (g.LogFile != stdout)
3701
0
#endif
3702
0
            ImFileClose(g.LogFile);
3703
0
        g.LogFile = NULL;
3704
0
    }
3705
0
    g.LogBuffer.clear();
3706
0
    g.DebugLogBuf.clear();
3707
0
    g.DebugLogIndex.clear();
3708
3709
0
    g.Initialized = false;
3710
0
}
3711
3712
// No specific ordering/dependency support, will see as needed
3713
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3714
0
{
3715
0
    ImGuiContext& g = *ctx;
3716
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3717
0
    g.Hooks.push_back(*hook);
3718
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3719
0
    return g.HookIdNext;
3720
0
}
3721
3722
// Deferred removal, avoiding issue with changing vector while iterating it
3723
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3724
0
{
3725
0
    ImGuiContext& g = *ctx;
3726
0
    IM_ASSERT(hook_id != 0);
3727
0
    for (int n = 0; n < g.Hooks.Size; n++)
3728
0
        if (g.Hooks[n].HookId == hook_id)
3729
0
            g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
3730
0
}
3731
3732
// Call context hooks (used by e.g. test engine)
3733
// We assume a small number of hooks so all stored in same array
3734
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3735
1.00M
{
3736
1.00M
    ImGuiContext& g = *ctx;
3737
1.00M
    for (int n = 0; n < g.Hooks.Size; n++)
3738
0
        if (g.Hooks[n].Type == hook_type)
3739
0
            g.Hooks[n].Callback(&g, &g.Hooks[n]);
3740
1.00M
}
3741
3742
3743
//-----------------------------------------------------------------------------
3744
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3745
//-----------------------------------------------------------------------------
3746
3747
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3748
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3749
10
{
3750
10
    memset(this, 0, sizeof(*this));
3751
10
    Ctx = ctx;
3752
10
    Name = ImStrdup(name);
3753
10
    NameBufLen = (int)strlen(name) + 1;
3754
10
    ID = ImHashStr(name);
3755
10
    IDStack.push_back(ID);
3756
10
    ViewportAllowPlatformMonitorExtend = -1;
3757
10
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3758
10
    MoveId = GetID("#MOVE");
3759
10
    TabId = GetID("#TAB");
3760
10
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3761
10
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3762
10
    AutoFitFramesX = AutoFitFramesY = -1;
3763
10
    AutoPosLastDirection = ImGuiDir_None;
3764
10
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3765
10
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3766
10
    LastFrameActive = -1;
3767
10
    LastFrameJustFocused = -1;
3768
10
    LastTimeActive = -1.0f;
3769
10
    FontWindowScale = FontDpiScale = 1.0f;
3770
10
    SettingsOffset = -1;
3771
10
    DockOrder = -1;
3772
10
    DrawList = &DrawListInst;
3773
10
    DrawList->_Data = &Ctx->DrawListSharedData;
3774
10
    DrawList->_OwnerName = Name;
3775
10
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3776
10
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3777
10
}
3778
3779
ImGuiWindow::~ImGuiWindow()
3780
0
{
3781
0
    IM_ASSERT(DrawList == &DrawListInst);
3782
0
    IM_DELETE(Name);
3783
0
    ColumnsStorage.clear_destruct();
3784
0
}
3785
3786
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3787
666k
{
3788
666k
    ImGuiID seed = IDStack.back();
3789
666k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3790
666k
    ImGuiContext& g = *Ctx;
3791
666k
    if (g.DebugHookIdInfo == id)
3792
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3793
666k
    return id;
3794
666k
}
3795
3796
ImGuiID ImGuiWindow::GetID(const void* ptr)
3797
0
{
3798
0
    ImGuiID seed = IDStack.back();
3799
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3800
0
    ImGuiContext& g = *Ctx;
3801
0
    if (g.DebugHookIdInfo == id)
3802
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3803
0
    return id;
3804
0
}
3805
3806
ImGuiID ImGuiWindow::GetID(int n)
3807
103k
{
3808
103k
    ImGuiID seed = IDStack.back();
3809
103k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3810
103k
    ImGuiContext& g = *Ctx;
3811
103k
    if (g.DebugHookIdInfo == id)
3812
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3813
103k
    return id;
3814
103k
}
3815
3816
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3817
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3818
0
{
3819
0
    ImGuiID seed = IDStack.back();
3820
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3821
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3822
0
    return id;
3823
0
}
3824
3825
static void SetCurrentWindow(ImGuiWindow* window)
3826
880k
{
3827
880k
    ImGuiContext& g = *GImGui;
3828
880k
    g.CurrentWindow = window;
3829
880k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3830
880k
    if (window)
3831
712k
    {
3832
712k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3833
712k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3834
712k
    }
3835
880k
}
3836
3837
void ImGui::GcCompactTransientMiscBuffers()
3838
0
{
3839
0
    ImGuiContext& g = *GImGui;
3840
0
    g.ItemFlagsStack.clear();
3841
0
    g.GroupStack.clear();
3842
0
    TableGcCompactSettings();
3843
0
}
3844
3845
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3846
// Not freed:
3847
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3848
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3849
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3850
1
{
3851
1
    window->MemoryCompacted = true;
3852
1
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3853
1
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3854
1
    window->IDStack.clear();
3855
1
    window->DrawList->_ClearFreeMemory();
3856
1
    window->DC.ChildWindows.clear();
3857
1
    window->DC.ItemWidthStack.clear();
3858
1
    window->DC.TextWrapPosStack.clear();
3859
1
}
3860
3861
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3862
0
{
3863
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3864
    // The other buffers tends to amortize much faster.
3865
0
    window->MemoryCompacted = false;
3866
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3867
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3868
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3869
0
}
3870
3871
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3872
2.53k
{
3873
2.53k
    ImGuiContext& g = *GImGui;
3874
3875
    // Clear previous active id
3876
2.53k
    if (g.ActiveId != 0)
3877
1.24k
    {
3878
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
3879
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3880
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3881
1.24k
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3882
0
        {
3883
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3884
0
            g.MovingWindow = NULL;
3885
0
        }
3886
3887
        // This could be written in a more general way (e.g associate a hook to ActiveId),
3888
        // but since this is currently quite an exception we'll leave it as is.
3889
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3890
1.24k
        if (g.InputTextState.ID == g.ActiveId)
3891
0
            InputTextDeactivateHook(g.ActiveId);
3892
1.24k
    }
3893
3894
    // Set active id
3895
2.53k
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3896
2.53k
    if (g.ActiveIdIsJustActivated)
3897
2.48k
    {
3898
2.48k
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3899
2.48k
        g.ActiveIdTimer = 0.0f;
3900
2.48k
        g.ActiveIdHasBeenPressedBefore = false;
3901
2.48k
        g.ActiveIdHasBeenEditedBefore = false;
3902
2.48k
        g.ActiveIdMouseButton = -1;
3903
2.48k
        if (id != 0)
3904
1.24k
        {
3905
1.24k
            g.LastActiveId = id;
3906
1.24k
            g.LastActiveIdTimer = 0.0f;
3907
1.24k
        }
3908
2.48k
    }
3909
2.53k
    g.ActiveId = id;
3910
2.53k
    g.ActiveIdAllowOverlap = false;
3911
2.53k
    g.ActiveIdNoClearOnFocusLoss = false;
3912
2.53k
    g.ActiveIdWindow = window;
3913
2.53k
    g.ActiveIdHasBeenEditedThisFrame = false;
3914
2.53k
    if (id)
3915
1.24k
    {
3916
1.24k
        g.ActiveIdIsAlive = id;
3917
1.24k
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
3918
1.24k
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
3919
1.24k
    }
3920
3921
    // Clear declaration of inputs claimed by the widget
3922
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3923
2.53k
    g.ActiveIdUsingNavDirMask = 0x00;
3924
2.53k
    g.ActiveIdUsingAllKeyboardKeys = false;
3925
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3926
    g.ActiveIdUsingNavInputMask = 0x00;
3927
#endif
3928
2.53k
}
3929
3930
void ImGui::ClearActiveID()
3931
1.28k
{
3932
1.28k
    SetActiveID(0, NULL); // g.ActiveId = 0;
3933
1.28k
}
3934
3935
void ImGui::SetHoveredID(ImGuiID id)
3936
802
{
3937
802
    ImGuiContext& g = *GImGui;
3938
802
    g.HoveredId = id;
3939
802
    g.HoveredIdAllowOverlap = false;
3940
802
    if (id != 0 && g.HoveredIdPreviousFrame != id)
3941
342
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3942
802
}
3943
3944
ImGuiID ImGui::GetHoveredID()
3945
0
{
3946
0
    ImGuiContext& g = *GImGui;
3947
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
3948
0
}
3949
3950
// This is called by ItemAdd().
3951
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
3952
void ImGui::KeepAliveID(ImGuiID id)
3953
579k
{
3954
579k
    ImGuiContext& g = *GImGui;
3955
579k
    if (g.ActiveId == id)
3956
11.7k
        g.ActiveIdIsAlive = id;
3957
579k
    if (g.ActiveIdPreviousFrame == id)
3958
11.7k
        g.ActiveIdPreviousFrameIsAlive = true;
3959
579k
}
3960
3961
void ImGui::MarkItemEdited(ImGuiID id)
3962
0
{
3963
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
3964
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
3965
0
    ImGuiContext& g = *GImGui;
3966
0
    if (g.ActiveId == id || g.ActiveId == 0)
3967
0
    {
3968
0
        g.ActiveIdHasBeenEditedThisFrame = true;
3969
0
        g.ActiveIdHasBeenEditedBefore = true;
3970
0
    }
3971
3972
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
3973
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
3974
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
3975
3976
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
3977
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
3978
0
}
3979
3980
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
3981
38.6k
{
3982
    // An active popup disable hovering on other windows (apart from its own children)
3983
    // FIXME-OPT: This could be cached/stored within the window.
3984
38.6k
    ImGuiContext& g = *GImGui;
3985
38.6k
    if (g.NavWindow)
3986
33.8k
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
3987
33.8k
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
3988
0
            {
3989
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
3990
                // NB: The 'else' is important because Modal windows are also Popups.
3991
0
                bool want_inhibit = false;
3992
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
3993
0
                    want_inhibit = true;
3994
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
3995
0
                    want_inhibit = true;
3996
3997
                // Inhibit hover unless the window is within the stack of our modal/popup
3998
0
                if (want_inhibit)
3999
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4000
0
                        return false;
4001
0
            }
4002
4003
    // Filter by viewport
4004
38.6k
    if (window->Viewport != g.MouseViewport)
4005
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4006
0
            return false;
4007
4008
38.6k
    return true;
4009
38.6k
}
4010
4011
// This is roughly matching the behavior of internal-facing ItemHoverable()
4012
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4013
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4014
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4015
0
{
4016
0
    ImGuiContext& g = *GImGui;
4017
0
    ImGuiWindow* window = g.CurrentWindow;
4018
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4019
0
    {
4020
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4021
0
            return false;
4022
0
        if (!IsItemFocused())
4023
0
            return false;
4024
0
    }
4025
0
    else
4026
0
    {
4027
        // Test for bounding box overlap, as updated as ItemAdd()
4028
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4029
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4030
0
            return false;
4031
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4032
4033
        // Done with rectangle culling so we can perform heavier checks now
4034
        // Test if we are hovering the right window (our window could be behind another window)
4035
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4036
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4037
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4038
        // the test that has been running for a long while.
4039
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4040
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
4041
0
                return false;
4042
4043
        // Test if another item is active (e.g. being dragged)
4044
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4045
0
            if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap)
4046
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4047
0
                    return false;
4048
4049
        // Test if interactions on this window are blocked by an active popup or modal.
4050
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4051
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4052
0
            return false;
4053
4054
        // Test if the item is disabled
4055
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4056
0
            return false;
4057
4058
        // Special handling for calling after Begin() which represent the title bar or tab.
4059
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4060
        // will never be overwritten so we need to detect the case.
4061
0
        if (g.LastItemData.ID == window->MoveId && window->WriteAccessed)
4062
0
            return false;
4063
0
    }
4064
4065
    // Handle hover delay
4066
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4067
0
    float delay;
4068
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4069
0
        delay = g.IO.HoverDelayNormal;
4070
0
    else if (flags & ImGuiHoveredFlags_DelayShort)
4071
0
        delay = g.IO.HoverDelayShort;
4072
0
    else
4073
0
        delay = 0.0f;
4074
0
    if (delay > 0.0f)
4075
0
    {
4076
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4077
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverDelayIdPreviousFrame != hover_delay_id))
4078
0
            g.HoverDelayTimer = 0.0f;
4079
0
        g.HoverDelayId = hover_delay_id;
4080
0
        return g.HoverDelayTimer >= delay;
4081
0
    }
4082
4083
0
    return true;
4084
0
}
4085
4086
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4087
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
4088
554k
{
4089
554k
    ImGuiContext& g = *GImGui;
4090
554k
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4091
870
        return false;
4092
4093
553k
    ImGuiWindow* window = g.CurrentWindow;
4094
553k
    if (g.HoveredWindow != window)
4095
501k
        return false;
4096
51.7k
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4097
17.8k
        return false;
4098
33.8k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4099
33.0k
        return false;
4100
4101
    // Done with rectangle culling so we can perform heavier checks now.
4102
802
    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
4103
802
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4104
0
    {
4105
0
        g.HoveredIdDisabled = true;
4106
0
        return false;
4107
0
    }
4108
4109
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4110
    // hover test in widgets code. We could also decide to split this function is two.
4111
802
    if (id != 0)
4112
802
        SetHoveredID(id);
4113
4114
    // When disabled we'll return false but still set HoveredId
4115
802
    if (item_flags & ImGuiItemFlags_Disabled)
4116
0
    {
4117
        // Release active id if turning disabled
4118
0
        if (g.ActiveId == id)
4119
0
            ClearActiveID();
4120
0
        g.HoveredIdDisabled = true;
4121
0
        return false;
4122
0
    }
4123
4124
802
    if (id != 0)
4125
802
    {
4126
        // [DEBUG] Item Picker tool!
4127
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
4128
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
4129
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
4130
802
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4131
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4132
802
        if (g.DebugItemPickerBreakId == id)
4133
0
            IM_DEBUG_BREAK();
4134
802
    }
4135
4136
802
    if (g.NavDisableMouseHover)
4137
57
        return false;
4138
4139
745
    return true;
4140
802
}
4141
4142
// FIXME: This is inlined/duplicated in ItemAdd()
4143
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4144
1.27k
{
4145
1.27k
    ImGuiContext& g = *GImGui;
4146
1.27k
    ImGuiWindow* window = g.CurrentWindow;
4147
1.27k
    if (!bb.Overlaps(window->ClipRect))
4148
59
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
4149
59
            if (!g.LogEnabled)
4150
59
                return true;
4151
1.21k
    return false;
4152
1.27k
}
4153
4154
// This is also inlined in ItemAdd()
4155
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4156
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4157
440k
{
4158
440k
    ImGuiContext& g = *GImGui;
4159
440k
    g.LastItemData.ID = item_id;
4160
440k
    g.LastItemData.InFlags = in_flags;
4161
440k
    g.LastItemData.StatusFlags = item_flags;
4162
440k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4163
440k
}
4164
4165
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4166
0
{
4167
0
    if (wrap_pos_x < 0.0f)
4168
0
        return 0.0f;
4169
4170
0
    ImGuiContext& g = *GImGui;
4171
0
    ImGuiWindow* window = g.CurrentWindow;
4172
0
    if (wrap_pos_x == 0.0f)
4173
0
    {
4174
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4175
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4176
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4177
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4178
        //else
4179
0
        wrap_pos_x = window->WorkRect.Max.x;
4180
0
    }
4181
0
    else if (wrap_pos_x > 0.0f)
4182
0
    {
4183
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4184
0
    }
4185
4186
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4187
0
}
4188
4189
// IM_ALLOC() == ImGui::MemAlloc()
4190
void* ImGui::MemAlloc(size_t size)
4191
3.70k
{
4192
3.70k
    if (ImGuiContext* ctx = GImGui)
4193
3.69k
        ctx->IO.MetricsActiveAllocations++;
4194
3.70k
    return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4195
3.70k
}
4196
4197
// IM_FREE() == ImGui::MemFree()
4198
void ImGui::MemFree(void* ptr)
4199
3.55k
{
4200
3.55k
    if (ptr)
4201
3.52k
        if (ImGuiContext* ctx = GImGui)
4202
3.52k
            ctx->IO.MetricsActiveAllocations--;
4203
3.55k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4204
3.55k
}
4205
4206
const char* ImGui::GetClipboardText()
4207
0
{
4208
0
    ImGuiContext& g = *GImGui;
4209
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4210
0
}
4211
4212
void ImGui::SetClipboardText(const char* text)
4213
0
{
4214
0
    ImGuiContext& g = *GImGui;
4215
0
    if (g.IO.SetClipboardTextFn)
4216
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4217
0
}
4218
4219
const char* ImGui::GetVersion()
4220
0
{
4221
0
    return IMGUI_VERSION;
4222
0
}
4223
4224
ImGuiIO& ImGui::GetIO()
4225
587k
{
4226
587k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4227
587k
    return GImGui->IO;
4228
587k
}
4229
4230
ImGuiPlatformIO& ImGui::GetPlatformIO()
4231
0
{
4232
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4233
0
    return GImGui->PlatformIO;
4234
0
}
4235
4236
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4237
ImDrawData* ImGui::GetDrawData()
4238
167k
{
4239
167k
    ImGuiContext& g = *GImGui;
4240
167k
    ImGuiViewportP* viewport = g.Viewports[0];
4241
167k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4242
167k
}
4243
4244
double ImGui::GetTime()
4245
24.5k
{
4246
24.5k
    return GImGui->Time;
4247
24.5k
}
4248
4249
int ImGui::GetFrameCount()
4250
0
{
4251
0
    return GImGui->FrameCount;
4252
0
}
4253
4254
static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4255
0
{
4256
    // Create the draw list on demand, because they are not frequently used for all viewports
4257
0
    ImGuiContext& g = *GImGui;
4258
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
4259
0
    ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
4260
0
    if (draw_list == NULL)
4261
0
    {
4262
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4263
0
        draw_list->_OwnerName = drawlist_name;
4264
0
        viewport->DrawLists[drawlist_no] = draw_list;
4265
0
    }
4266
4267
    // Our ImDrawList system requires that there is always a command
4268
0
    if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
4269
0
    {
4270
0
        draw_list->_ResetForNewFrame();
4271
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4272
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4273
0
        viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
4274
0
    }
4275
0
    return draw_list;
4276
0
}
4277
4278
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4279
0
{
4280
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4281
0
}
4282
4283
ImDrawList* ImGui::GetBackgroundDrawList()
4284
0
{
4285
0
    ImGuiContext& g = *GImGui;
4286
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4287
0
}
4288
4289
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4290
0
{
4291
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4292
0
}
4293
4294
ImDrawList* ImGui::GetForegroundDrawList()
4295
0
{
4296
0
    ImGuiContext& g = *GImGui;
4297
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4298
0
}
4299
4300
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4301
0
{
4302
0
    return &GImGui->DrawListSharedData;
4303
0
}
4304
4305
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4306
1.20k
{
4307
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4308
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4309
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4310
1.20k
    ImGuiContext& g = *GImGui;
4311
1.20k
    FocusWindow(window);
4312
1.20k
    SetActiveID(window->MoveId, window);
4313
1.20k
    g.NavDisableHighlight = true;
4314
1.20k
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4315
1.20k
    g.ActiveIdNoClearOnFocusLoss = true;
4316
1.20k
    SetActiveIdUsingAllKeyboardKeys();
4317
4318
1.20k
    bool can_move_window = true;
4319
1.20k
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4320
1.17k
        can_move_window = false;
4321
1.20k
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4322
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4323
0
            can_move_window = false;
4324
1.20k
    if (can_move_window)
4325
36
        g.MovingWindow = window;
4326
1.20k
}
4327
4328
// We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4329
// - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node.
4330
// - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window.
4331
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node)
4332
3
{
4333
3
    ImGuiContext& g = *GImGui;
4334
3
    bool can_undock_node = false;
4335
3
    if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0)
4336
0
    {
4337
        // Can undock if:
4338
        // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy)
4339
        // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows)
4340
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4341
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4342
0
            if (undock_floating_node || root_node->IsDockSpace())
4343
0
                can_undock_node = true;
4344
0
    }
4345
4346
3
    const bool clicked = IsMouseClicked(0);
4347
3
    const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
4348
3
    if (can_undock_node && dragging)
4349
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4350
3
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4351
3
        StartMouseMovingWindow(window);
4352
3
}
4353
4354
// Handle mouse moving window
4355
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4356
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4357
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4358
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4359
void ImGui::UpdateMouseMovingWindowNewFrame()
4360
167k
{
4361
167k
    ImGuiContext& g = *GImGui;
4362
167k
    if (g.MovingWindow != NULL)
4363
218
    {
4364
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4365
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4366
218
        KeepAliveID(g.ActiveId);
4367
218
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4368
218
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4369
4370
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4371
218
        const bool window_disappared = ((!moving_window->WasActive && !moving_window->Active) || moving_window->Viewport == NULL);
4372
218
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4373
182
        {
4374
182
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4375
182
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4376
55
            {
4377
55
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4378
55
                if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4379
0
                {
4380
0
                    moving_window->Viewport->Pos = pos;
4381
0
                    moving_window->Viewport->UpdateWorkRect();
4382
0
                }
4383
55
            }
4384
182
            FocusWindow(g.MovingWindow);
4385
182
        }
4386
36
        else
4387
36
        {
4388
36
            if (!window_disappared)
4389
36
            {
4390
                // Try to merge the window back into the main viewport.
4391
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4392
36
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4393
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4394
4395
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4396
36
                if (!IsDragDropPayloadBeingAccepted())
4397
36
                    g.MouseViewport = moving_window->Viewport;
4398
4399
                // Clear the NoInput window flag set by the Viewport system
4400
36
                moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; // FIXME-VIEWPORT: Test engine managed to crash here because Viewport was NULL.
4401
36
            }
4402
4403
36
            g.MovingWindow = NULL;
4404
36
            ClearActiveID();
4405
36
        }
4406
218
    }
4407
166k
    else
4408
166k
    {
4409
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4410
166k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4411
11.3k
        {
4412
11.3k
            KeepAliveID(g.ActiveId);
4413
11.3k
            if (!g.IO.MouseDown[0])
4414
1.17k
                ClearActiveID();
4415
11.3k
        }
4416
166k
    }
4417
167k
}
4418
4419
// Initiate moving window when clicking on empty space or title bar.
4420
// Handle left-click and right-click focus.
4421
void ImGui::UpdateMouseMovingWindowEndFrame()
4422
167k
{
4423
167k
    ImGuiContext& g = *GImGui;
4424
167k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4425
11.2k
        return;
4426
4427
    // Unless we just made a window/popup appear
4428
155k
    if (g.NavWindow && g.NavWindow->Appearing)
4429
3
        return;
4430
4431
    // Click on empty space to focus window and start moving
4432
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4433
155k
    if (g.IO.MouseClicked[0])
4434
5.94k
    {
4435
        // Handle the edge case of a popup being closed while clicking in its empty space.
4436
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4437
5.94k
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4438
5.94k
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4439
4440
5.94k
        if (root_window != NULL && !is_closed_popup)
4441
1.20k
        {
4442
1.20k
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4443
4444
            // Cancel moving if clicked outside of title bar
4445
1.20k
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4446
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4447
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4448
0
                        g.MovingWindow = NULL;
4449
4450
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4451
1.20k
            if (g.HoveredIdDisabled)
4452
0
                g.MovingWindow = NULL;
4453
1.20k
        }
4454
4.74k
        else if (root_window == NULL && g.NavWindow != NULL)
4455
721
        {
4456
            // Clicking on void disable focus
4457
721
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4458
721
        }
4459
5.94k
    }
4460
4461
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4462
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4463
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4464
155k
    if (g.IO.MouseClicked[1])
4465
993
    {
4466
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4467
        // This is where we can trim the popup stack.
4468
993
        ImGuiWindow* modal = GetTopMostPopupModal();
4469
993
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4470
993
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4471
993
    }
4472
155k
}
4473
4474
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4475
// Need to keep in sync with SetWindowPos()
4476
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4477
0
{
4478
0
    window->Pos += delta;
4479
0
    window->ClipRect.Translate(delta);
4480
0
    window->OuterRectClipped.Translate(delta);
4481
0
    window->InnerRect.Translate(delta);
4482
0
    window->DC.CursorPos += delta;
4483
0
    window->DC.CursorStartPos += delta;
4484
0
    window->DC.CursorMaxPos += delta;
4485
0
    window->DC.IdealMaxPos += delta;
4486
0
}
4487
4488
static void ScaleWindow(ImGuiWindow* window, float scale)
4489
0
{
4490
0
    ImVec2 origin = window->Viewport->Pos;
4491
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4492
0
    window->Size = ImFloor(window->Size * scale);
4493
0
    window->SizeFull = ImFloor(window->SizeFull * scale);
4494
0
    window->ContentSize = ImFloor(window->ContentSize * scale);
4495
0
}
4496
4497
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4498
669k
{
4499
669k
    return (window->Active) && (!window->Hidden);
4500
669k
}
4501
4502
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4503
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4504
167k
{
4505
167k
    ImGuiContext& g = *GImGui;
4506
167k
    ImGuiIO& io = g.IO;
4507
167k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4508
4509
    // Find the window hovered by mouse:
4510
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4511
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4512
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4513
167k
    bool clear_hovered_windows = false;
4514
167k
    FindHoveredWindow();
4515
167k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4516
4517
    // Modal windows prevents mouse from hovering behind them.
4518
167k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4519
167k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4520
0
        clear_hovered_windows = true;
4521
4522
    // Disabled mouse?
4523
167k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4524
0
        clear_hovered_windows = true;
4525
4526
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4527
    // won't report hovering nor request capture even while dragging over our windows afterward.
4528
167k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4529
167k
    const bool has_open_modal = (modal_window != NULL);
4530
167k
    int mouse_earliest_down = -1;
4531
167k
    bool mouse_any_down = false;
4532
1.00M
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4533
835k
    {
4534
835k
        if (io.MouseClicked[i])
4535
10.8k
        {
4536
10.8k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4537
10.8k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4538
10.8k
        }
4539
835k
        mouse_any_down |= io.MouseDown[i];
4540
835k
        if (io.MouseDown[i])
4541
90.3k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4542
68.2k
                mouse_earliest_down = i;
4543
835k
    }
4544
167k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4545
167k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4546
4547
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4548
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4549
167k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4550
167k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4551
35.5k
        clear_hovered_windows = true;
4552
4553
167k
    if (clear_hovered_windows)
4554
35.5k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4555
4556
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4557
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4558
167k
    if (g.WantCaptureMouseNextFrame != -1)
4559
0
    {
4560
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4561
0
    }
4562
167k
    else
4563
167k
    {
4564
167k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4565
167k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4566
167k
    }
4567
4568
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4569
167k
    if (g.WantCaptureKeyboardNextFrame != -1)
4570
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4571
167k
    else
4572
167k
        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4573
167k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4574
77.4k
        io.WantCaptureKeyboard = true;
4575
4576
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4577
167k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4578
167k
}
4579
4580
void ImGui::NewFrame()
4581
167k
{
4582
167k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4583
167k
    ImGuiContext& g = *GImGui;
4584
4585
    // Remove pending delete hooks before frame start.
4586
    // This deferred removal avoid issues of removal while iterating the hook vector
4587
167k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4588
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4589
0
            g.Hooks.erase(&g.Hooks[n]);
4590
4591
167k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4592
4593
    // Check and assert for various common IO and Configuration mistakes
4594
167k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4595
167k
    ErrorCheckNewFrameSanityChecks();
4596
167k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4597
4598
    // Load settings on first frame, save settings when modified (after a delay)
4599
167k
    UpdateSettings();
4600
4601
167k
    g.Time += g.IO.DeltaTime;
4602
167k
    g.WithinFrameScope = true;
4603
167k
    g.FrameCount += 1;
4604
167k
    g.TooltipOverrideCount = 0;
4605
167k
    g.WindowsActiveCount = 0;
4606
167k
    g.MenusIdSubmittedThisFrame.resize(0);
4607
4608
    // Calculate frame-rate for the user, as a purely luxurious feature
4609
167k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4610
167k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4611
167k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4612
167k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4613
167k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4614
4615
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4616
167k
    g.InputEventsTrail.resize(0);
4617
167k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4618
4619
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4620
167k
    UpdateViewportsNewFrame();
4621
4622
    // Setup current font and draw list shared data
4623
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4624
167k
    g.IO.Fonts->Locked = true;
4625
167k
    SetCurrentFont(GetDefaultFont());
4626
167k
    IM_ASSERT(g.Font->IsLoaded());
4627
167k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4628
334k
    for (int n = 0; n < g.Viewports.Size; n++)
4629
167k
        virtual_space.Add(g.Viewports[n]->GetMainRect());
4630
167k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4631
167k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4632
167k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4633
167k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4634
167k
    if (g.Style.AntiAliasedLines)
4635
167k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4636
167k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4637
167k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4638
167k
    if (g.Style.AntiAliasedFill)
4639
167k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4640
167k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4641
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4642
4643
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4644
334k
    for (int n = 0; n < g.Viewports.Size; n++)
4645
167k
    {
4646
167k
        ImGuiViewportP* viewport = g.Viewports[n];
4647
167k
        viewport->DrawData = NULL;
4648
167k
        viewport->DrawDataP.Clear();
4649
167k
    }
4650
4651
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4652
167k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4653
18
        KeepAliveID(g.DragDropPayload.SourceId);
4654
4655
    // Update HoveredId data
4656
167k
    if (!g.HoveredIdPreviousFrame)
4657
166k
        g.HoveredIdTimer = 0.0f;
4658
167k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4659
166k
        g.HoveredIdNotActiveTimer = 0.0f;
4660
167k
    if (g.HoveredId)
4661
802
        g.HoveredIdTimer += g.IO.DeltaTime;
4662
167k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4663
728
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4664
167k
    g.HoveredIdPreviousFrame = g.HoveredId;
4665
167k
    g.HoveredId = 0;
4666
167k
    g.HoveredIdAllowOverlap = false;
4667
167k
    g.HoveredIdDisabled = false;
4668
4669
    // Clear ActiveID if the item is not alive anymore.
4670
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4671
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4672
167k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4673
0
    {
4674
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4675
0
        ClearActiveID();
4676
0
    }
4677
4678
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4679
167k
    if (g.ActiveId)
4680
11.6k
        g.ActiveIdTimer += g.IO.DeltaTime;
4681
167k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4682
167k
    g.ActiveIdPreviousFrame = g.ActiveId;
4683
167k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4684
167k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4685
167k
    g.ActiveIdIsAlive = 0;
4686
167k
    g.ActiveIdHasBeenEditedThisFrame = false;
4687
167k
    g.ActiveIdPreviousFrameIsAlive = false;
4688
167k
    g.ActiveIdIsJustActivated = false;
4689
167k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4690
0
        g.TempInputId = 0;
4691
167k
    if (g.ActiveId == 0)
4692
155k
    {
4693
155k
        g.ActiveIdUsingNavDirMask = 0x00;
4694
155k
        g.ActiveIdUsingAllKeyboardKeys = false;
4695
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4696
        g.ActiveIdUsingNavInputMask = 0x00;
4697
#endif
4698
155k
    }
4699
4700
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4701
    if (g.ActiveId == 0)
4702
        g.ActiveIdUsingNavInputMask = 0;
4703
    else if (g.ActiveIdUsingNavInputMask != 0)
4704
    {
4705
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4706
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4707
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4708
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4709
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4710
            IM_ASSERT(0); // Other values unsupported
4711
    }
4712
#endif
4713
4714
    // Update hover delay for IsItemHovered() with delays and tooltips
4715
167k
    g.HoverDelayIdPreviousFrame = g.HoverDelayId;
4716
167k
    if (g.HoverDelayId != 0)
4717
0
    {
4718
        //if (g.IO.MouseDelta.x == 0.0f && g.IO.MouseDelta.y == 0.0f) // Need design/flags
4719
0
        g.HoverDelayTimer += g.IO.DeltaTime;
4720
0
        g.HoverDelayClearTimer = 0.0f;
4721
0
        g.HoverDelayId = 0;
4722
0
    }
4723
167k
    else if (g.HoverDelayTimer > 0.0f)
4724
0
    {
4725
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4726
0
        g.HoverDelayClearTimer += g.IO.DeltaTime;
4727
0
        if (g.HoverDelayClearTimer >= ImMax(0.20f, g.IO.DeltaTime * 2.0f)) // ~6 frames at 30 Hz + allow for low framerate
4728
0
            g.HoverDelayTimer = g.HoverDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4729
0
    }
4730
4731
    // Drag and drop
4732
167k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4733
167k
    g.DragDropAcceptIdCurr = 0;
4734
167k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4735
167k
    g.DragDropWithinSource = false;
4736
167k
    g.DragDropWithinTarget = false;
4737
167k
    g.DragDropHoldJustPressedId = 0;
4738
4739
    // Close popups on focus lost (currently wip/opt-in)
4740
    //if (g.IO.AppFocusLost)
4741
    //    ClosePopupsExceptModals();
4742
4743
    // Update keyboard input state
4744
167k
    UpdateKeyboardInputs();
4745
4746
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4747
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4748
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4749
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4750
4751
    // Update gamepad/keyboard navigation
4752
167k
    NavUpdate();
4753
4754
    // Update mouse input state
4755
167k
    UpdateMouseInputs();
4756
4757
    // Undocking
4758
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4759
167k
    DockContextNewFrameUpdateUndocking(&g);
4760
4761
    // Find hovered window
4762
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4763
167k
    UpdateHoveredWindowAndCaptureFlags();
4764
4765
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4766
167k
    UpdateMouseMovingWindowNewFrame();
4767
4768
    // Background darkening/whitening
4769
167k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4770
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4771
167k
    else
4772
167k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4773
4774
167k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4775
167k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4776
4777
    // Platform IME data: reset for the frame
4778
167k
    g.PlatformImeDataPrev = g.PlatformImeData;
4779
167k
    g.PlatformImeData.WantVisible = false;
4780
4781
    // Mouse wheel scrolling, scale
4782
167k
    UpdateMouseWheel();
4783
4784
    // Mark all windows as not visible and compact unused memory.
4785
167k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4786
167k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4787
733k
    for (int i = 0; i != g.Windows.Size; i++)
4788
566k
    {
4789
566k
        ImGuiWindow* window = g.Windows[i];
4790
566k
        window->WasActive = window->Active;
4791
566k
        window->Active = false;
4792
566k
        window->WriteAccessed = false;
4793
566k
        window->BeginCountPreviousFrame = window->BeginCount;
4794
566k
        window->BeginCount = 0;
4795
4796
        // Garbage collect transient buffers of recently unused windows
4797
566k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4798
1
            GcCompactTransientWindowBuffers(window);
4799
566k
    }
4800
4801
    // Garbage collect transient buffers of recently unused tables
4802
167k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4803
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4804
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4805
167k
    for (int i = 0; i < g.TablesTempData.Size; i++)
4806
0
        if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time)
4807
0
            TableGcCompactTransientBuffers(&g.TablesTempData[i]);
4808
167k
    if (g.GcCompactAll)
4809
0
        GcCompactTransientMiscBuffers();
4810
167k
    g.GcCompactAll = false;
4811
4812
    // Closing the focused window restore focus to the first active root window in descending z-order
4813
167k
    if (g.NavWindow && !g.NavWindow->WasActive)
4814
0
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
4815
4816
    // No window should be open at the beginning of the frame.
4817
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4818
167k
    g.CurrentWindowStack.resize(0);
4819
167k
    g.BeginPopupStack.resize(0);
4820
167k
    g.ItemFlagsStack.resize(0);
4821
167k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4822
167k
    g.GroupStack.resize(0);
4823
4824
    // Docking
4825
167k
    DockContextNewFrameUpdateDocking(&g);
4826
4827
    // [DEBUG] Update debug features
4828
167k
    UpdateDebugToolItemPicker();
4829
167k
    UpdateDebugToolStackQueries();
4830
167k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4831
0
        g.DebugLocateId = 0;
4832
167k
    if (g.DebugLogClipperAutoDisableFrames > 0 && --g.DebugLogClipperAutoDisableFrames == 0)
4833
0
    {
4834
0
        DebugLog("(Auto-disabled ImGuiDebugLogFlags_EventClipper to avoid spamming)\n");
4835
0
        g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
4836
0
    }
4837
4838
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
4839
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4840
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4841
167k
    g.WithinFrameScopeWithImplicitWindow = true;
4842
167k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
4843
167k
    Begin("Debug##Default");
4844
167k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4845
4846
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
4847
    // allowing to validate correct Begin/End behavior in user code.
4848
167k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
4849
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
4850
167k
    else
4851
167k
        g.DebugBeginReturnValueCullDepth = -1;
4852
4853
167k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
4854
167k
}
4855
4856
// FIXME: Add a more explicit sort order in the window structure.
4857
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
4858
0
{
4859
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
4860
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
4861
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
4862
0
        return d;
4863
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
4864
0
        return d;
4865
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
4866
0
}
4867
4868
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
4869
566k
{
4870
566k
    out_sorted_windows->push_back(window);
4871
566k
    if (window->Active)
4872
272k
    {
4873
272k
        int count = window->DC.ChildWindows.Size;
4874
272k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
4875
376k
        for (int i = 0; i < count; i++)
4876
103k
        {
4877
103k
            ImGuiWindow* child = window->DC.ChildWindows[i];
4878
103k
            if (child->Active)
4879
103k
                AddWindowToSortBuffer(out_sorted_windows, child);
4880
103k
        }
4881
272k
    }
4882
566k
}
4883
4884
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
4885
262k
{
4886
262k
    if (draw_list->CmdBuffer.Size == 0)
4887
0
        return;
4888
262k
    if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL)
4889
733
        return;
4890
4891
    // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
4892
    // May trigger for you if you are using PrimXXX functions incorrectly.
4893
261k
    IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
4894
261k
    IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
4895
261k
    if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
4896
261k
        IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
4897
4898
    // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
4899
    // If this assert triggers because you are drawing lots of stuff manually:
4900
    // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
4901
    //   Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
4902
    // - If you want large meshes with more than 64K vertices, you can either:
4903
    //   (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
4904
    //       Most example backends already support this from 1.71. Pre-1.71 backends won't.
4905
    //       Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
4906
    //   (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
4907
    //       Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
4908
    //         glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
4909
    //       Your own engine or render API may use different parameters or function calls to specify index sizes.
4910
    //       2 and 4 bytes indices are generally supported by most graphics API.
4911
    // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
4912
    //   the 64K limit to split your draw commands in multiple draw lists.
4913
261k
    if (sizeof(ImDrawIdx) == 2)
4914
261k
        IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
4915
4916
261k
    out_list->push_back(draw_list);
4917
261k
}
4918
4919
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
4920
262k
{
4921
262k
    ImGuiContext& g = *GImGui;
4922
262k
    ImGuiViewportP* viewport = window->Viewport;
4923
262k
    g.IO.MetricsRenderWindows++;
4924
262k
    if (window->Flags & ImGuiWindowFlags_DockNodeHost)
4925
0
        window->DrawList->ChannelsMerge();
4926
262k
    AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
4927
365k
    for (int i = 0; i < window->DC.ChildWindows.Size; i++)
4928
103k
    {
4929
103k
        ImGuiWindow* child = window->DC.ChildWindows[i];
4930
103k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
4931
94.5k
            AddWindowToDrawData(child, layer);
4932
103k
    }
4933
262k
}
4934
4935
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
4936
167k
{
4937
167k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
4938
167k
}
4939
4940
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
4941
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
4942
167k
{
4943
167k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
4944
167k
}
4945
4946
void ImDrawDataBuilder::FlattenIntoSingleLayer()
4947
167k
{
4948
167k
    int n = Layers[0].Size;
4949
167k
    int size = n;
4950
334k
    for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
4951
167k
        size += Layers[i].Size;
4952
167k
    Layers[0].resize(size);
4953
334k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
4954
167k
    {
4955
167k
        ImVector<ImDrawList*>& layer = Layers[layer_n];
4956
167k
        if (layer.empty())
4957
166k
            continue;
4958
393
        memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
4959
393
        n += layer.Size;
4960
393
        layer.resize(0);
4961
393
    }
4962
167k
}
4963
4964
static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
4965
167k
{
4966
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
4967
    // and to allow applications/backends to easily skip rendering.
4968
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
4969
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
4970
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
4971
167k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
4972
4973
167k
    ImGuiIO& io = ImGui::GetIO();
4974
167k
    ImDrawData* draw_data = &viewport->DrawDataP;
4975
167k
    viewport->DrawData = draw_data; // Make publicly accessible
4976
167k
    draw_data->Valid = true;
4977
167k
    draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
4978
167k
    draw_data->CmdListsCount = draw_lists->Size;
4979
167k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
4980
167k
    draw_data->DisplayPos = viewport->Pos;
4981
167k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
4982
167k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
4983
167k
    draw_data->OwnerViewport = viewport;
4984
428k
    for (int n = 0; n < draw_lists->Size; n++)
4985
261k
    {
4986
261k
        ImDrawList* draw_list = draw_lists->Data[n];
4987
261k
        draw_list->_PopUnusedDrawCmd();
4988
261k
        draw_data->TotalVtxCount += draw_list->VtxBuffer.Size;
4989
261k
        draw_data->TotalIdxCount += draw_list->IdxBuffer.Size;
4990
261k
    }
4991
167k
}
4992
4993
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
4994
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
4995
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
4996
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
4997
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
4998
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
4999
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5000
880k
{
5001
880k
    ImGuiWindow* window = GetCurrentWindow();
5002
880k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5003
880k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5004
880k
}
5005
5006
void ImGui::PopClipRect()
5007
440k
{
5008
440k
    ImGuiWindow* window = GetCurrentWindow();
5009
440k
    window->DrawList->PopClipRect();
5010
440k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5011
440k
}
5012
5013
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5014
0
{
5015
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5016
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5017
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5018
0
    return window;
5019
0
}
5020
5021
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5022
0
{
5023
0
    if ((col & IM_COL32_A_MASK) == 0)
5024
0
        return;
5025
5026
0
    ImGuiViewportP* viewport = window->Viewport;
5027
0
    ImRect viewport_rect = viewport->GetMainRect();
5028
5029
    // Draw behind window by moving the draw command at the FRONT of the draw list
5030
0
    {
5031
        // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
5032
        // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5033
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5034
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5035
0
        if (draw_list->CmdBuffer.Size == 0)
5036
0
            draw_list->AddDrawCmd();
5037
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged
5038
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5039
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5040
0
        IM_ASSERT(cmd.ElemCount == 6);
5041
0
        draw_list->CmdBuffer.pop_back();
5042
0
        draw_list->CmdBuffer.push_front(cmd);
5043
0
        draw_list->PopClipRect();
5044
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5045
0
    }
5046
5047
    // Draw over sibling docking nodes in a same docking tree
5048
0
    if (window->RootWindow->DockIsActive)
5049
0
    {
5050
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5051
0
        if (draw_list->CmdBuffer.Size == 0)
5052
0
            draw_list->AddDrawCmd();
5053
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5054
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5055
0
        draw_list->PopClipRect();
5056
0
    }
5057
0
}
5058
5059
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5060
0
{
5061
0
    ImGuiContext& g = *GImGui;
5062
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5063
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5064
0
    {
5065
0
        ImGuiWindow* window = g.Windows[i];
5066
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5067
0
            continue;
5068
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5069
0
            break;
5070
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5071
0
            bottom_most_visible_window = window;
5072
0
    }
5073
0
    return bottom_most_visible_window;
5074
0
}
5075
5076
static void ImGui::RenderDimmedBackgrounds()
5077
167k
{
5078
167k
    ImGuiContext& g = *GImGui;
5079
167k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5080
167k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5081
167k
        return;
5082
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5083
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5084
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5085
0
        return;
5086
5087
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5088
0
    if (dim_bg_for_modal)
5089
0
    {
5090
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5091
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5092
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
5093
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5094
0
    }
5095
0
    else if (dim_bg_for_window_list)
5096
0
    {
5097
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5098
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5099
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5100
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5101
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5102
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5103
5104
        // Draw border around CTRL+Tab target window
5105
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5106
0
        ImGuiViewport* viewport = window->Viewport;
5107
0
        float distance = g.FontSize;
5108
0
        ImRect bb = window->Rect();
5109
0
        bb.Expand(distance);
5110
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5111
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5112
0
        if (window->DrawList->CmdBuffer.Size == 0)
5113
0
            window->DrawList->AddDrawCmd();
5114
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5115
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5116
0
        window->DrawList->PopClipRect();
5117
0
    }
5118
5119
    // Draw dimming background on _other_ viewports than the ones our windows are in
5120
0
    for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
5121
0
    {
5122
0
        ImGuiViewportP* viewport = g.Viewports[viewport_n];
5123
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5124
0
            continue;
5125
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5126
0
            continue;
5127
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5128
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5129
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5130
0
    }
5131
0
}
5132
5133
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5134
void ImGui::EndFrame()
5135
334k
{
5136
334k
    ImGuiContext& g = *GImGui;
5137
334k
    IM_ASSERT(g.Initialized);
5138
5139
    // Don't process EndFrame() multiple times.
5140
334k
    if (g.FrameCountEnded == g.FrameCount)
5141
167k
        return;
5142
167k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5143
5144
167k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5145
5146
167k
    ErrorCheckEndFrameSanityChecks();
5147
5148
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5149
167k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5150
167k
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5151
0
    {
5152
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5153
0
        IMGUI_DEBUG_LOG_IO("Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5154
0
        if (viewport == NULL)
5155
0
            viewport = GetMainViewport();
5156
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5157
        if (viewport->PlatformHandleRaw == NULL && g.IO.ImeWindowHandle != NULL)
5158
        {
5159
            viewport->PlatformHandleRaw = g.IO.ImeWindowHandle;
5160
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5161
            viewport->PlatformHandleRaw = NULL;
5162
        }
5163
        else
5164
#endif
5165
0
        {
5166
0
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5167
0
        }
5168
0
    }
5169
5170
    // Hide implicit/fallback "Debug" window if it hasn't been used
5171
167k
    g.WithinFrameScopeWithImplicitWindow = false;
5172
167k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5173
167k
        g.CurrentWindow->Active = false;
5174
167k
    End();
5175
5176
    // Update navigation: CTRL+Tab, wrap-around requests
5177
167k
    NavEndFrame();
5178
5179
    // Update docking
5180
167k
    DockContextEndFrame(&g);
5181
5182
167k
    SetCurrentViewport(NULL, NULL);
5183
5184
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5185
167k
    if (g.DragDropActive)
5186
24
    {
5187
24
        bool is_delivered = g.DragDropPayload.Delivery;
5188
24
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5189
24
        if (is_delivered || is_elapsed)
5190
3
            ClearDragDrop();
5191
24
    }
5192
5193
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5194
167k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5195
0
    {
5196
0
        g.DragDropWithinSource = true;
5197
0
        SetTooltip("...");
5198
0
        g.DragDropWithinSource = false;
5199
0
    }
5200
5201
    // End frame
5202
167k
    g.WithinFrameScope = false;
5203
167k
    g.FrameCountEnded = g.FrameCount;
5204
5205
    // Initiate moving window + handle left-click and right-click focus
5206
167k
    UpdateMouseMovingWindowEndFrame();
5207
5208
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5209
167k
    UpdateViewportsEndFrame();
5210
5211
    // Sort the window list so that all child windows are after their parent
5212
    // We cannot do that on FocusWindow() because children may not exist yet
5213
167k
    g.WindowsTempSortBuffer.resize(0);
5214
167k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5215
733k
    for (int i = 0; i != g.Windows.Size; i++)
5216
566k
    {
5217
566k
        ImGuiWindow* window = g.Windows[i];
5218
566k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5219
103k
            continue;
5220
462k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5221
462k
    }
5222
5223
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5224
167k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5225
167k
    g.Windows.swap(g.WindowsTempSortBuffer);
5226
167k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5227
5228
    // Unlock font atlas
5229
167k
    g.IO.Fonts->Locked = false;
5230
5231
    // Clear Input data for next frame
5232
167k
    g.IO.AppFocusLost = false;
5233
167k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5234
167k
    g.IO.InputQueueCharacters.resize(0);
5235
5236
167k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5237
167k
}
5238
5239
// Prepare the data for rendering so you can call GetDrawData()
5240
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5241
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5242
void ImGui::Render()
5243
167k
{
5244
167k
    ImGuiContext& g = *GImGui;
5245
167k
    IM_ASSERT(g.Initialized);
5246
5247
167k
    if (g.FrameCountEnded != g.FrameCount)
5248
167k
        EndFrame();
5249
167k
    const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount);
5250
167k
    g.FrameCountRendered = g.FrameCount;
5251
167k
    g.IO.MetricsRenderWindows = 0;
5252
5253
167k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5254
5255
    // Add background ImDrawList (for each active viewport)
5256
334k
    for (int n = 0; n != g.Viewports.Size; n++)
5257
167k
    {
5258
167k
        ImGuiViewportP* viewport = g.Viewports[n];
5259
167k
        viewport->DrawDataBuilder.Clear();
5260
167k
        if (viewport->DrawLists[0] != NULL)
5261
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5262
167k
    }
5263
5264
    // Add ImDrawList to render
5265
167k
    ImGuiWindow* windows_to_render_top_most[2];
5266
167k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5267
167k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5268
733k
    for (int n = 0; n != g.Windows.Size; n++)
5269
566k
    {
5270
566k
        ImGuiWindow* window = g.Windows[n];
5271
566k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5272
566k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5273
167k
            AddRootWindowToDrawData(window);
5274
566k
    }
5275
501k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5276
334k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5277
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5278
5279
    // Draw modal/window whitening backgrounds
5280
167k
    if (first_render_of_frame)
5281
167k
        RenderDimmedBackgrounds();
5282
5283
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5284
167k
    if (g.IO.MouseDrawCursor && first_render_of_frame && g.MouseCursor != ImGuiMouseCursor_None)
5285
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5286
5287
    // Setup ImDrawData structures for end-user
5288
167k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5289
334k
    for (int n = 0; n < g.Viewports.Size; n++)
5290
167k
    {
5291
167k
        ImGuiViewportP* viewport = g.Viewports[n];
5292
167k
        viewport->DrawDataBuilder.FlattenIntoSingleLayer();
5293
5294
        // Add foreground ImDrawList (for each active viewport)
5295
167k
        if (viewport->DrawLists[1] != NULL)
5296
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5297
5298
167k
        SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
5299
167k
        ImDrawData* draw_data = viewport->DrawData;
5300
167k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5301
167k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5302
167k
    }
5303
5304
167k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5305
167k
}
5306
5307
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5308
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5309
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5310
340k
{
5311
340k
    ImGuiContext& g = *GImGui;
5312
5313
340k
    const char* text_display_end;
5314
340k
    if (hide_text_after_double_hash)
5315
334k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5316
5.88k
    else
5317
5.88k
        text_display_end = text_end;
5318
5319
340k
    ImFont* font = g.Font;
5320
340k
    const float font_size = g.FontSize;
5321
340k
    if (text == text_display_end)
5322
83
        return ImVec2(0.0f, font_size);
5323
339k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5324
5325
    // Round
5326
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5327
    // FIXME: Investigate using ceilf or e.g.
5328
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5329
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5330
339k
    text_size.x = IM_FLOOR(text_size.x + 0.99999f);
5331
5332
339k
    return text_size;
5333
340k
}
5334
5335
// Find window given position, search front-to-back
5336
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5337
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5338
// called, aka before the next Begin(). Moving window isn't affected.
5339
static void FindHoveredWindow()
5340
167k
{
5341
167k
    ImGuiContext& g = *GImGui;
5342
5343
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5344
167k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5345
167k
    if (g.MovingWindow)
5346
218
        g.MovingWindow->Viewport = g.MouseViewport;
5347
5348
167k
    ImGuiWindow* hovered_window = NULL;
5349
167k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5350
167k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5351
218
        hovered_window = g.MovingWindow;
5352
5353
167k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5354
167k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5355
634k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5356
492k
    {
5357
492k
        ImGuiWindow* window = g.Windows[i];
5358
492k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5359
492k
        if (!window->Active || window->Hidden)
5360
254k
            continue;
5361
238k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5362
67
            continue;
5363
238k
        IM_ASSERT(window->Viewport);
5364
238k
        if (window->Viewport != g.MouseViewport)
5365
0
            continue;
5366
5367
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5368
238k
        ImRect bb(window->OuterRectClipped);
5369
238k
        if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
5370
94.5k
            bb.Expand(padding_regular);
5371
143k
        else
5372
143k
            bb.Expand(padding_for_resize);
5373
238k
        if (!bb.Contains(g.IO.MousePos))
5374
212k
            continue;
5375
5376
        // Support for one rectangular hole in any given window
5377
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5378
25.5k
        if (window->HitTestHoleSize.x != 0)
5379
0
        {
5380
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5381
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5382
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5383
0
                continue;
5384
0
        }
5385
5386
25.5k
        if (hovered_window == NULL)
5387
25.4k
            hovered_window = window;
5388
25.5k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5389
25.5k
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5390
25.4k
            hovered_window_ignoring_moving_window = window;
5391
25.5k
        if (hovered_window && hovered_window_ignoring_moving_window)
5392
25.4k
            break;
5393
25.5k
    }
5394
5395
167k
    g.HoveredWindow = hovered_window;
5396
167k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5397
5398
167k
    if (g.MovingWindow)
5399
218
        g.MovingWindow->Viewport = moving_window_viewport;
5400
167k
}
5401
5402
bool ImGui::IsItemActive()
5403
334k
{
5404
334k
    ImGuiContext& g = *GImGui;
5405
334k
    if (g.ActiveId)
5406
21.0k
        return g.ActiveId == g.LastItemData.ID;
5407
313k
    return false;
5408
334k
}
5409
5410
bool ImGui::IsItemActivated()
5411
0
{
5412
0
    ImGuiContext& g = *GImGui;
5413
0
    if (g.ActiveId)
5414
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5415
0
            return true;
5416
0
    return false;
5417
0
}
5418
5419
bool ImGui::IsItemDeactivated()
5420
0
{
5421
0
    ImGuiContext& g = *GImGui;
5422
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5423
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5424
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5425
0
}
5426
5427
bool ImGui::IsItemDeactivatedAfterEdit()
5428
0
{
5429
0
    ImGuiContext& g = *GImGui;
5430
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5431
0
}
5432
5433
// == GetItemID() == GetFocusID()
5434
bool ImGui::IsItemFocused()
5435
0
{
5436
0
    ImGuiContext& g = *GImGui;
5437
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5438
0
        return false;
5439
5440
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5441
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5442
0
    ImGuiWindow* window = g.CurrentWindow;
5443
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5444
0
        return false;
5445
5446
0
    return true;
5447
0
}
5448
5449
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5450
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5451
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5452
0
{
5453
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5454
0
}
5455
5456
bool ImGui::IsItemToggledOpen()
5457
0
{
5458
0
    ImGuiContext& g = *GImGui;
5459
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5460
0
}
5461
5462
bool ImGui::IsItemToggledSelection()
5463
0
{
5464
0
    ImGuiContext& g = *GImGui;
5465
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5466
0
}
5467
5468
bool ImGui::IsAnyItemHovered()
5469
0
{
5470
0
    ImGuiContext& g = *GImGui;
5471
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5472
0
}
5473
5474
bool ImGui::IsAnyItemActive()
5475
0
{
5476
0
    ImGuiContext& g = *GImGui;
5477
0
    return g.ActiveId != 0;
5478
0
}
5479
5480
bool ImGui::IsAnyItemFocused()
5481
0
{
5482
0
    ImGuiContext& g = *GImGui;
5483
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5484
0
}
5485
5486
bool ImGui::IsItemVisible()
5487
0
{
5488
0
    ImGuiContext& g = *GImGui;
5489
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5490
0
}
5491
5492
bool ImGui::IsItemEdited()
5493
0
{
5494
0
    ImGuiContext& g = *GImGui;
5495
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5496
0
}
5497
5498
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5499
// FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
5500
void ImGui::SetItemAllowOverlap()
5501
0
{
5502
0
    ImGuiContext& g = *GImGui;
5503
0
    ImGuiID id = g.LastItemData.ID;
5504
0
    if (g.HoveredId == id)
5505
0
        g.HoveredIdAllowOverlap = true;
5506
0
    if (g.ActiveId == id)
5507
0
        g.ActiveIdAllowOverlap = true;
5508
0
}
5509
5510
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5511
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5512
1.28k
{
5513
1.28k
    ImGuiContext& g = *GImGui;
5514
1.28k
    IM_ASSERT(g.ActiveId != 0);
5515
1.28k
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5516
1.28k
    g.ActiveIdUsingAllKeyboardKeys = true;
5517
1.28k
    NavMoveRequestCancel();
5518
1.28k
}
5519
5520
ImGuiID ImGui::GetItemID()
5521
0
{
5522
0
    ImGuiContext& g = *GImGui;
5523
0
    return g.LastItemData.ID;
5524
0
}
5525
5526
ImVec2 ImGui::GetItemRectMin()
5527
0
{
5528
0
    ImGuiContext& g = *GImGui;
5529
0
    return g.LastItemData.Rect.Min;
5530
0
}
5531
5532
ImVec2 ImGui::GetItemRectMax()
5533
0
{
5534
0
    ImGuiContext& g = *GImGui;
5535
0
    return g.LastItemData.Rect.Max;
5536
0
}
5537
5538
ImVec2 ImGui::GetItemRectSize()
5539
0
{
5540
0
    ImGuiContext& g = *GImGui;
5541
0
    return g.LastItemData.Rect.GetSize();
5542
0
}
5543
5544
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
5545
103k
{
5546
103k
    ImGuiContext& g = *GImGui;
5547
103k
    ImGuiWindow* parent_window = g.CurrentWindow;
5548
5549
103k
    flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking;
5550
103k
    flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove);  // Inherit the NoMove flag
5551
5552
    // Size
5553
103k
    const ImVec2 content_avail = GetContentRegionAvail();
5554
103k
    ImVec2 size = ImFloor(size_arg);
5555
103k
    const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
5556
103k
    if (size.x <= 0.0f)
5557
90.0k
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too many issues)
5558
103k
    if (size.y <= 0.0f)
5559
86.9k
        size.y = ImMax(content_avail.y + size.y, 4.0f);
5560
103k
    SetNextWindowSize(size);
5561
5562
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5563
103k
    const char* temp_window_name;
5564
103k
    if (name)
5565
103k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5566
0
    else
5567
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5568
5569
103k
    const float backup_border_size = g.Style.ChildBorderSize;
5570
103k
    if (!border)
5571
58.4k
        g.Style.ChildBorderSize = 0.0f;
5572
103k
    bool ret = Begin(temp_window_name, NULL, flags);
5573
103k
    g.Style.ChildBorderSize = backup_border_size;
5574
5575
103k
    ImGuiWindow* child_window = g.CurrentWindow;
5576
103k
    child_window->ChildId = id;
5577
103k
    child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
5578
5579
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5580
    // While this is not really documented/defined, it seems that the expected thing to do.
5581
103k
    if (child_window->BeginCount == 1)
5582
103k
        parent_window->DC.CursorPos = child_window->Pos;
5583
5584
    // Process navigation-in immediately so NavInit can run on first frame
5585
    // Can enter a child if (A) it has navigatable items or (B) it can be scrolled.
5586
103k
    if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5587
6
    {
5588
6
        FocusWindow(child_window);
5589
6
        NavInitWindow(child_window, false);
5590
6
        SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5591
6
        g.ActiveIdSource = g.NavInputSource;
5592
6
    }
5593
103k
    return ret;
5594
103k
}
5595
5596
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5597
103k
{
5598
103k
    ImGuiWindow* window = GetCurrentWindow();
5599
103k
    return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
5600
103k
}
5601
5602
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5603
0
{
5604
0
    IM_ASSERT(id != 0);
5605
0
    return BeginChildEx(NULL, id, size_arg, border, extra_flags);
5606
0
}
5607
5608
void ImGui::EndChild()
5609
103k
{
5610
103k
    ImGuiContext& g = *GImGui;
5611
103k
    ImGuiWindow* window = g.CurrentWindow;
5612
5613
103k
    IM_ASSERT(g.WithinEndChild == false);
5614
103k
    IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5615
5616
103k
    g.WithinEndChild = true;
5617
103k
    if (window->BeginCount > 1)
5618
0
    {
5619
0
        End();
5620
0
    }
5621
103k
    else
5622
103k
    {
5623
103k
        ImVec2 sz = window->Size;
5624
103k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
5625
90.0k
            sz.x = ImMax(4.0f, sz.x);
5626
103k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
5627
86.9k
            sz.y = ImMax(4.0f, sz.y);
5628
103k
        End();
5629
5630
103k
        ImGuiWindow* parent_window = g.CurrentWindow;
5631
103k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
5632
103k
        ItemSize(sz);
5633
103k
        if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavWindowHasScrollY) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
5634
13.2k
        {
5635
13.2k
            ItemAdd(bb, window->ChildId);
5636
13.2k
            RenderNavHighlight(bb, window->ChildId);
5637
5638
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5639
13.2k
            if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
5640
10.3k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5641
13.2k
        }
5642
90.1k
        else
5643
90.1k
        {
5644
            // Not navigable into
5645
90.1k
            ItemAdd(bb, 0);
5646
5647
            // But when flattened we directly reach items, adjust active layer mask accordingly
5648
90.1k
            if (window->Flags & ImGuiWindowFlags_NavFlattened)
5649
0
                parent_window->DC.NavLayersActiveMaskNext |= window->DC.NavLayersActiveMaskNext;
5650
90.1k
        }
5651
103k
        if (g.HoveredWindow == window)
5652
23.5k
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5653
103k
    }
5654
103k
    g.WithinEndChild = false;
5655
103k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5656
103k
}
5657
5658
// Helper to create a child window / scrolling region that looks like a normal widget frame.
5659
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
5660
0
{
5661
0
    ImGuiContext& g = *GImGui;
5662
0
    const ImGuiStyle& style = g.Style;
5663
0
    PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
5664
0
    PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
5665
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
5666
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
5667
0
    bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
5668
0
    PopStyleVar(3);
5669
0
    PopStyleColor();
5670
0
    return ret;
5671
0
}
5672
5673
void ImGui::EndChildFrame()
5674
0
{
5675
0
    EndChild();
5676
0
}
5677
5678
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5679
3.96k
{
5680
3.96k
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5681
3.96k
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5682
3.96k
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5683
3.96k
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5684
3.96k
}
5685
5686
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5687
440k
{
5688
440k
    ImGuiContext& g = *GImGui;
5689
440k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5690
440k
}
5691
5692
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5693
440k
{
5694
440k
    ImGuiID id = ImHashStr(name);
5695
440k
    return FindWindowByID(id);
5696
440k
}
5697
5698
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5699
0
{
5700
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5701
0
    window->ViewportPos = main_viewport->Pos;
5702
0
    if (settings->ViewportId)
5703
0
    {
5704
0
        window->ViewportId = settings->ViewportId;
5705
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5706
0
    }
5707
0
    window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5708
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5709
0
        window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
5710
0
    window->Collapsed = settings->Collapsed;
5711
0
    window->DockId = settings->DockId;
5712
0
    window->DockOrder = settings->DockOrder;
5713
0
}
5714
5715
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5716
440k
{
5717
440k
    ImGuiContext& g = *GImGui;
5718
5719
440k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5720
440k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5721
440k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5722
7
    {
5723
7
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5724
7
        g.WindowsFocusOrder.push_back(window);
5725
7
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5726
7
    }
5727
440k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5728
0
    {
5729
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5730
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5731
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5732
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5733
0
        window->FocusOrder = -1;
5734
0
    }
5735
440k
    window->IsExplicitChild = new_is_explicit_child;
5736
440k
}
5737
5738
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5739
10
{
5740
    // Initial window state with e.g. default/arbitrary window position
5741
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5742
10
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5743
10
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5744
10
    window->ViewportPos = main_viewport->Pos;
5745
10
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5746
5747
10
    if (settings != NULL)
5748
0
    {
5749
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5750
0
        ApplyWindowSettings(window, settings);
5751
0
    }
5752
10
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5753
5754
10
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5755
1
    {
5756
1
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5757
1
        window->AutoFitOnlyGrows = false;
5758
1
    }
5759
9
    else
5760
9
    {
5761
9
        if (window->Size.x <= 0.0f)
5762
9
            window->AutoFitFramesX = 2;
5763
9
        if (window->Size.y <= 0.0f)
5764
9
            window->AutoFitFramesY = 2;
5765
9
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5766
9
    }
5767
10
}
5768
5769
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5770
10
{
5771
    // Create window the first time
5772
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5773
10
    ImGuiContext& g = *GImGui;
5774
10
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5775
10
    window->Flags = flags;
5776
10
    g.WindowsById.SetVoidPtr(window->ID, window);
5777
5778
10
    ImGuiWindowSettings* settings = NULL;
5779
10
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5780
6
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5781
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5782
5783
10
    InitOrLoadWindowSettings(window, settings);
5784
5785
10
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5786
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5787
10
    else
5788
10
        g.Windows.push_back(window);
5789
5790
10
    return window;
5791
10
}
5792
5793
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5794
0
{
5795
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5796
0
}
5797
5798
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5799
668k
{
5800
668k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5801
668k
}
5802
5803
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5804
877k
{
5805
877k
    ImGuiContext& g = *GImGui;
5806
877k
    ImVec2 new_size = size_desired;
5807
877k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5808
0
    {
5809
        // Using -1,-1 on either X/Y axis to preserve the current size.
5810
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
5811
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5812
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5813
0
        if (g.NextWindowData.SizeCallback)
5814
0
        {
5815
0
            ImGuiSizeCallbackData data;
5816
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
5817
0
            data.Pos = window->Pos;
5818
0
            data.CurrentSize = window->SizeFull;
5819
0
            data.DesiredSize = new_size;
5820
0
            g.NextWindowData.SizeCallback(&data);
5821
0
            new_size = data.DesiredSize;
5822
0
        }
5823
0
        new_size.x = IM_FLOOR(new_size.x);
5824
0
        new_size.y = IM_FLOOR(new_size.y);
5825
0
    }
5826
5827
    // Minimum size
5828
877k
    if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
5829
668k
    {
5830
668k
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5831
668k
        new_size = ImMax(new_size, g.Style.WindowMinSize);
5832
668k
        const float minimum_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f);
5833
668k
        new_size.y = ImMax(new_size.y, minimum_height); // Reduce artifacts with very small windows
5834
668k
    }
5835
877k
    return new_size;
5836
877k
}
5837
5838
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5839
440k
{
5840
440k
    bool preserve_old_content_sizes = false;
5841
440k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5842
63.6k
        preserve_old_content_sizes = true;
5843
376k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
5844
8.89k
        preserve_old_content_sizes = true;
5845
440k
    if (preserve_old_content_sizes)
5846
72.4k
    {
5847
72.4k
        *content_size_current = window->ContentSize;
5848
72.4k
        *content_size_ideal = window->ContentSizeIdeal;
5849
72.4k
        return;
5850
72.4k
    }
5851
5852
367k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
5853
367k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
5854
367k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
5855
367k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
5856
367k
}
5857
5858
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
5859
440k
{
5860
440k
    ImGuiContext& g = *GImGui;
5861
440k
    ImGuiStyle& style = g.Style;
5862
440k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
5863
440k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
5864
440k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
5865
440k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
5866
440k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
5867
2.36k
    {
5868
        // Tooltip always resize
5869
2.36k
        return size_desired;
5870
2.36k
    }
5871
437k
    else
5872
437k
    {
5873
        // Maximum window size is determined by the viewport size or monitor size
5874
437k
        const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
5875
437k
        const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
5876
437k
        ImVec2 size_min = style.WindowMinSize;
5877
437k
        if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5878
0
            size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
5879
5880
437k
        ImVec2 avail_size = window->Viewport->WorkSize;
5881
437k
        if (window->ViewportOwned)
5882
0
            avail_size = ImVec2(FLT_MAX, FLT_MAX);
5883
437k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
5884
437k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
5885
0
            avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
5886
437k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
5887
5888
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
5889
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
5890
437k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5891
437k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
5892
437k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
5893
437k
        if (will_have_scrollbar_x)
5894
103k
            size_auto_fit.y += style.ScrollbarSize;
5895
437k
        if (will_have_scrollbar_y)
5896
4.38k
            size_auto_fit.x += style.ScrollbarSize;
5897
437k
        return size_auto_fit;
5898
437k
    }
5899
440k
}
5900
5901
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
5902
0
{
5903
0
    ImVec2 size_contents_current;
5904
0
    ImVec2 size_contents_ideal;
5905
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
5906
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
5907
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5908
0
    return size_final;
5909
0
}
5910
5911
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
5912
376k
{
5913
376k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
5914
2.36k
        return ImGuiCol_PopupBg;
5915
374k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
5916
103k
        return ImGuiCol_ChildBg;
5917
270k
    return ImGuiCol_WindowBg;
5918
374k
}
5919
5920
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
5921
97
{
5922
97
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
5923
97
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
5924
97
    ImVec2 size_expected = pos_max - pos_min;
5925
97
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
5926
97
    *out_pos = pos_min;
5927
97
    if (corner_norm.x == 0.0f)
5928
0
        out_pos->x -= (size_constrained.x - size_expected.x);
5929
97
    if (corner_norm.y == 0.0f)
5930
0
        out_pos->y -= (size_constrained.y - size_expected.y);
5931
97
    *out_size = size_constrained;
5932
97
}
5933
5934
// Data for resizing from corner
5935
struct ImGuiResizeGripDef
5936
{
5937
    ImVec2  CornerPosN;
5938
    ImVec2  InnerDir;
5939
    int     AngleMin12, AngleMax12;
5940
};
5941
static const ImGuiResizeGripDef resize_grip_def[4] =
5942
{
5943
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
5944
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
5945
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
5946
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
5947
};
5948
5949
// Data for resizing from borders
5950
struct ImGuiResizeBorderDef
5951
{
5952
    ImVec2 InnerDir;
5953
    ImVec2 SegmentN1, SegmentN2;
5954
    float  OuterAngle;
5955
};
5956
static const ImGuiResizeBorderDef resize_border_def[4] =
5957
{
5958
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
5959
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
5960
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
5961
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
5962
};
5963
5964
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
5965
0
{
5966
0
    ImRect rect = window->Rect();
5967
0
    if (thickness == 0.0f)
5968
0
        rect.Max -= ImVec2(1, 1);
5969
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
5970
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
5971
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
5972
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
5973
0
    IM_ASSERT(0);
5974
0
    return ImRect();
5975
0
}
5976
5977
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
5978
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
5979
0
{
5980
0
    IM_ASSERT(n >= 0 && n < 4);
5981
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
5982
0
    id = ImHashStr("#RESIZE", 0, id);
5983
0
    id = ImHashData(&n, sizeof(int), id);
5984
0
    return id;
5985
0
}
5986
5987
// Borders (Left, Right, Up, Down)
5988
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
5989
0
{
5990
0
    IM_ASSERT(dir >= 0 && dir < 4);
5991
0
    int n = (int)dir + 4;
5992
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
5993
0
    id = ImHashStr("#RESIZE", 0, id);
5994
0
    id = ImHashData(&n, sizeof(int), id);
5995
0
    return id;
5996
0
}
5997
5998
// Handle resize for: Resize Grips, Borders, Gamepad
5999
// Return true when using auto-fit (double-click on resize grip)
6000
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6001
376k
{
6002
376k
    ImGuiContext& g = *GImGui;
6003
376k
    ImGuiWindowFlags flags = window->Flags;
6004
6005
376k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6006
105k
        return false;
6007
270k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6008
167k
        return false;
6009
6010
103k
    bool ret_auto_fit = false;
6011
103k
    const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
6012
103k
    const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6013
103k
    const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
6014
103k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6015
6016
103k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6017
103k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6018
6019
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6020
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6021
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6022
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6023
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6024
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6025
103k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6026
103k
    if (clip_with_viewport_rect)
6027
103k
        window->ClipRect = window->Viewport->GetMainRect();
6028
6029
    // Resize grips and borders are on layer 1
6030
103k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6031
6032
    // Manual resize grips
6033
103k
    PushID("#RESIZE");
6034
206k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6035
103k
    {
6036
103k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6037
103k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6038
6039
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6040
103k
        bool hovered, held;
6041
103k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6042
103k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6043
103k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6044
103k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6045
103k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6046
103k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6047
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6048
103k
        if (hovered || held)
6049
147
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6050
6051
103k
        if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)
6052
6
        {
6053
            // Manual auto-fit when double-clicking
6054
6
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6055
6
            ret_auto_fit = true;
6056
6
            ClearActiveID();
6057
6
        }
6058
103k
        else if (held)
6059
97
        {
6060
            // Resize from any of the four corners
6061
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6062
97
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
6063
97
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
6064
97
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6065
97
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6066
97
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6067
97
        }
6068
6069
        // Only lower-left grip is visible before hovering/activating
6070
103k
        if (resize_grip_n == 0 || held || hovered)
6071
103k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6072
103k
    }
6073
103k
    for (int border_n = 0; border_n < resize_border_count; border_n++)
6074
0
    {
6075
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6076
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6077
6078
0
        bool hovered, held;
6079
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6080
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6081
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6082
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6083
        //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6084
0
        if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
6085
0
        {
6086
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6087
0
            if (held)
6088
0
                *border_held = border_n;
6089
0
        }
6090
0
        if (held)
6091
0
        {
6092
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);
6093
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left  ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up   ? visibility_rect.Max.y : +FLT_MAX);
6094
0
            ImVec2 border_target = window->Pos;
6095
0
            border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
6096
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6097
0
            CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6098
0
        }
6099
0
    }
6100
103k
    PopID();
6101
6102
    // Restore nav layer
6103
103k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6104
6105
    // Navigation resize (keyboard/gamepad)
6106
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6107
    // Not even sure the callback works here.
6108
103k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6109
0
    {
6110
0
        ImVec2 nav_resize_dir;
6111
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6112
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6113
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6114
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6115
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6116
0
        {
6117
0
            const float NAV_RESIZE_SPEED = 600.0f;
6118
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6119
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6120
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, visibility_rect.Min - window->Pos - window->Size); // We need Pos+Size >= visibility_rect.Min, so Size >= visibility_rect.Min - Pos, so size_delta >= visibility_rect.Min - window->Pos - window->Size
6121
0
            g.NavWindowingToggleLayer = false;
6122
0
            g.NavDisableMouseHover = true;
6123
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6124
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaSize);
6125
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6126
0
            {
6127
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6128
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6129
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6130
0
            }
6131
0
        }
6132
0
    }
6133
6134
    // Apply back modified position/size to window
6135
103k
    if (size_target.x != FLT_MAX)
6136
103
    {
6137
103
        window->SizeFull = size_target;
6138
103
        MarkIniSettingsDirty(window);
6139
103
    }
6140
103k
    if (pos_target.x != FLT_MAX)
6141
97
    {
6142
97
        window->Pos = ImFloor(pos_target);
6143
97
        MarkIniSettingsDirty(window);
6144
97
    }
6145
6146
103k
    window->Size = window->SizeFull;
6147
103k
    return ret_auto_fit;
6148
270k
}
6149
6150
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6151
336k
{
6152
336k
    ImGuiContext& g = *GImGui;
6153
336k
    ImVec2 size_for_clamping = window->Size;
6154
336k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6155
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6156
336k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6157
336k
}
6158
6159
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6160
376k
{
6161
376k
    ImGuiContext& g = *GImGui;
6162
376k
    float rounding = window->WindowRounding;
6163
376k
    float border_size = window->WindowBorderSize;
6164
376k
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6165
317k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6166
6167
376k
    int border_held = window->ResizeBorderHeld;
6168
376k
    if (border_held != -1)
6169
0
    {
6170
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_held];
6171
0
        ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
6172
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6173
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6174
0
        window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
6175
0
    }
6176
376k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6177
0
    {
6178
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6179
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6180
0
    }
6181
376k
}
6182
6183
// Draw background and borders
6184
// Draw and handle scrollbars
6185
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6186
440k
{
6187
440k
    ImGuiContext& g = *GImGui;
6188
440k
    ImGuiStyle& style = g.Style;
6189
440k
    ImGuiWindowFlags flags = window->Flags;
6190
6191
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6192
440k
    IM_ASSERT(window->BeginCount == 0);
6193
440k
    window->SkipItems = false;
6194
6195
    // Draw window + handle manual resize
6196
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6197
440k
    const float window_rounding = window->WindowRounding;
6198
440k
    const float window_border_size = window->WindowBorderSize;
6199
440k
    if (window->Collapsed)
6200
63.6k
    {
6201
        // Title bar only
6202
63.6k
        const float backup_border_size = style.FrameBorderSize;
6203
63.6k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6204
63.6k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6205
63.6k
        if (window->ViewportOwned)
6206
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6207
63.6k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6208
63.6k
        g.Style.FrameBorderSize = backup_border_size;
6209
63.6k
    }
6210
376k
    else
6211
376k
    {
6212
        // Window background
6213
376k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6214
376k
        {
6215
376k
            bool is_docking_transparent_payload = false;
6216
376k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6217
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6218
0
                    is_docking_transparent_payload = true;
6219
6220
376k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6221
376k
            if (window->ViewportOwned)
6222
0
            {
6223
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6224
0
                if (is_docking_transparent_payload)
6225
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6226
0
            }
6227
376k
            else
6228
376k
            {
6229
                // Adjust alpha. For docking
6230
376k
                bool override_alpha = false;
6231
376k
                float alpha = 1.0f;
6232
376k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6233
0
                {
6234
0
                    alpha = g.NextWindowData.BgAlphaVal;
6235
0
                    override_alpha = true;
6236
0
                }
6237
376k
                if (is_docking_transparent_payload)
6238
0
                {
6239
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6240
0
                    override_alpha = true;
6241
0
                }
6242
376k
                if (override_alpha)
6243
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6244
376k
            }
6245
6246
            // Render, for docked windows and host windows we ensure bg goes before decorations
6247
376k
            if (window->DockIsActive)
6248
0
                window->DockNode->LastBgColor = bg_col;
6249
376k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6250
376k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6251
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6252
376k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6253
376k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6254
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6255
376k
        }
6256
376k
        if (window->DockIsActive)
6257
0
            window->DockNode->IsBgDrawnThisFrame = true;
6258
6259
        // Title bar
6260
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6261
        // in order for their pos/size to be matching their undocking state.)
6262
376k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6263
270k
        {
6264
270k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6265
270k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6266
270k
        }
6267
6268
        // Menu bar
6269
376k
        if (flags & ImGuiWindowFlags_MenuBar)
6270
0
        {
6271
0
            ImRect menu_bar_rect = window->MenuBarRect();
6272
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6273
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6274
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6275
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6276
0
        }
6277
6278
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6279
376k
        ImGuiDockNode* node = window->DockNode;
6280
376k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6281
0
        {
6282
0
            float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
6283
0
            float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
6284
0
            ImVec2 p = node->Pos;
6285
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6286
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6287
0
            KeepAliveID(unhide_id);
6288
0
            bool hovered, held;
6289
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6290
0
                node->WantHiddenTabBarToggle = true;
6291
0
            else if (held && IsMouseDragging(0))
6292
0
                StartMouseMovingWindowOrNode(window, node, true);
6293
6294
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6295
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6296
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6297
0
        }
6298
6299
        // Scrollbars
6300
376k
        if (window->ScrollbarX)
6301
103k
            Scrollbar(ImGuiAxis_X);
6302
376k
        if (window->ScrollbarY)
6303
21.3k
            Scrollbar(ImGuiAxis_Y);
6304
6305
        // Render resize grips (after their input handling so we don't have a frame of latency)
6306
376k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6307
270k
        {
6308
541k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6309
270k
            {
6310
270k
                const ImU32 col = resize_grip_col[resize_grip_n];
6311
270k
                if ((col & IM_COL32_A_MASK) == 0)
6312
167k
                    continue;
6313
103k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6314
103k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6315
103k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6316
103k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6317
103k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6318
103k
                window->DrawList->PathFillConvex(col);
6319
103k
            }
6320
270k
        }
6321
6322
        // Borders (for dock node host they will be rendered over after the tab bar)
6323
376k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6324
376k
            RenderWindowOuterBorders(window);
6325
376k
    }
6326
440k
}
6327
6328
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6329
// Render title text, collapse button, close button
6330
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6331
334k
{
6332
334k
    ImGuiContext& g = *GImGui;
6333
334k
    ImGuiStyle& style = g.Style;
6334
334k
    ImGuiWindowFlags flags = window->Flags;
6335
6336
334k
    const bool has_close_button = (p_open != NULL);
6337
334k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6338
6339
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6340
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6341
334k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6342
334k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6343
334k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6344
6345
    // Layout buttons
6346
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6347
334k
    float pad_l = style.FramePadding.x;
6348
334k
    float pad_r = style.FramePadding.x;
6349
334k
    float button_sz = g.FontSize;
6350
334k
    ImVec2 close_button_pos;
6351
334k
    ImVec2 collapse_button_pos;
6352
334k
    if (has_close_button)
6353
0
    {
6354
0
        pad_r += button_sz;
6355
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6356
0
    }
6357
334k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6358
0
    {
6359
0
        pad_r += button_sz;
6360
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6361
0
    }
6362
334k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6363
334k
    {
6364
334k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
6365
334k
        pad_l += button_sz;
6366
334k
    }
6367
6368
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6369
334k
    if (has_collapse_button)
6370
334k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6371
0
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6372
6373
    // Close button
6374
334k
    if (has_close_button)
6375
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6376
0
            *p_open = false;
6377
6378
334k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6379
334k
    g.CurrentItemFlags = item_flags_backup;
6380
6381
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6382
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6383
334k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6384
334k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6385
6386
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6387
    // while uncentered title text will still reach edges correctly.
6388
334k
    if (pad_l > style.FramePadding.x)
6389
334k
        pad_l += g.Style.ItemInnerSpacing.x;
6390
334k
    if (pad_r > style.FramePadding.x)
6391
0
        pad_r += g.Style.ItemInnerSpacing.x;
6392
334k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6393
0
    {
6394
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6395
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6396
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6397
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6398
0
    }
6399
6400
334k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6401
334k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6402
334k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6403
0
    {
6404
0
        ImVec2 marker_pos;
6405
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6406
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6407
0
        if (marker_pos.x > layout_r.Min.x)
6408
0
        {
6409
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6410
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6411
0
        }
6412
0
    }
6413
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6414
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6415
334k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6416
334k
}
6417
6418
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6419
440k
{
6420
440k
    window->ParentWindow = parent_window;
6421
440k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6422
440k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6423
103k
    {
6424
103k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6425
103k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6426
103k
            window->RootWindow = parent_window->RootWindow;
6427
103k
    }
6428
440k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6429
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6430
440k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6431
103k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6432
440k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6433
0
    {
6434
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6435
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6436
0
    }
6437
440k
}
6438
6439
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6440
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6441
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6442
// - Window             // FindBlockingModal() returns Modal1
6443
//   - Window           //                  .. returns Modal1
6444
//   - Modal1           //                  .. returns Modal2
6445
//      - Window        //                  .. returns Modal2
6446
//          - Window    //                  .. returns Modal2
6447
//          - Modal2    //                  .. returns Modal2
6448
// Notes:
6449
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6450
//   Only difference is here we check for ->Active/WasActive but it may be unecessary.
6451
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6452
727
{
6453
727
    ImGuiContext& g = *GImGui;
6454
727
    if (g.OpenPopupStack.Size <= 0)
6455
727
        return NULL;
6456
6457
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6458
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
6459
0
    {
6460
0
        ImGuiWindow* popup_window = g.OpenPopupStack.Data[i].Window;
6461
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6462
0
            continue;
6463
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6464
0
            continue;
6465
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6466
0
            return popup_window;
6467
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window is rendered over last modal, no render order change needed.
6468
0
            break;
6469
0
        for (ImGuiWindow* parent = popup_window->ParentWindowInBeginStack->RootWindow; parent != NULL; parent = parent->ParentWindowInBeginStack->RootWindow)
6470
0
            if (IsWindowWithinBeginStackOf(window, parent))
6471
0
                return popup_window;                                // Place window above its begin stack parent.
6472
0
    }
6473
0
    return NULL;
6474
0
}
6475
6476
// Push a new Dear ImGui window to add widgets to.
6477
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6478
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6479
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6480
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6481
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6482
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6483
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6484
440k
{
6485
440k
    ImGuiContext& g = *GImGui;
6486
440k
    const ImGuiStyle& style = g.Style;
6487
440k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6488
440k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6489
440k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6490
6491
    // Find or create
6492
440k
    ImGuiWindow* window = FindWindowByName(name);
6493
440k
    const bool window_just_created = (window == NULL);
6494
440k
    if (window_just_created)
6495
10
        window = CreateNewWindow(name, flags);
6496
6497
    // Automatically disable manual moving/resizing when NoInputs is set
6498
440k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6499
2.36k
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6500
6501
440k
    if (flags & ImGuiWindowFlags_NavFlattened)
6502
440k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6503
6504
440k
    const int current_frame = g.FrameCount;
6505
440k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6506
440k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6507
6508
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6509
440k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6510
440k
    if (flags & ImGuiWindowFlags_Popup)
6511
0
    {
6512
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6513
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6514
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6515
0
    }
6516
6517
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6518
440k
    const bool window_was_appearing = window->Appearing;
6519
440k
    if (first_begin_of_the_frame)
6520
440k
    {
6521
440k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6522
440k
        window->Appearing = window_just_activated_by_user;
6523
440k
        if (window->Appearing)
6524
1.98k
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6525
440k
        window->FlagsPreviousFrame = window->Flags;
6526
440k
        window->Flags = (ImGuiWindowFlags)flags;
6527
440k
        window->LastFrameActive = current_frame;
6528
440k
        window->LastTimeActive = (float)g.Time;
6529
440k
        window->BeginOrderWithinParent = 0;
6530
440k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6531
440k
    }
6532
0
    else
6533
0
    {
6534
0
        flags = window->Flags;
6535
0
    }
6536
6537
    // Docking
6538
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6539
440k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6540
440k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6541
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6542
440k
    if (first_begin_of_the_frame)
6543
440k
    {
6544
440k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6545
440k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6546
440k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6547
440k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6548
440k
        if (has_dock_node || new_auto_dock_node)
6549
0
        {
6550
0
            BeginDocked(window, p_open);
6551
0
            flags = window->Flags;
6552
0
            if (window->DockIsActive)
6553
0
            {
6554
0
                IM_ASSERT(window->DockNode != NULL);
6555
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6556
0
            }
6557
6558
            // Amend the Appearing flag
6559
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6560
0
            {
6561
0
                window->Appearing = true;
6562
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6563
0
            }
6564
0
        }
6565
440k
        else
6566
440k
        {
6567
440k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6568
440k
        }
6569
440k
    }
6570
6571
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6572
440k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6573
440k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6574
440k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6575
6576
    // We allow window memory to be compacted so recreate the base stack when needed.
6577
440k
    if (window->IDStack.Size == 0)
6578
0
        window->IDStack.push_back(window->ID);
6579
6580
    // Add to stack
6581
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6582
440k
    g.CurrentWindow = window;
6583
440k
    ImGuiWindowStackData window_stack_data;
6584
440k
    window_stack_data.Window = window;
6585
440k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6586
440k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6587
440k
    g.CurrentWindowStack.push_back(window_stack_data);
6588
440k
    if (flags & ImGuiWindowFlags_ChildMenu)
6589
0
        g.BeginMenuCount++;
6590
6591
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6592
440k
    if (first_begin_of_the_frame)
6593
440k
    {
6594
440k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6595
440k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6596
440k
    }
6597
6598
    // Add to focus scope stack
6599
440k
    PushFocusScope(window->ID);
6600
440k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6601
440k
    g.CurrentWindow = NULL;
6602
6603
    // Add to popup stack
6604
440k
    if (flags & ImGuiWindowFlags_Popup)
6605
0
    {
6606
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6607
0
        popup_ref.Window = window;
6608
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6609
0
        g.BeginPopupStack.push_back(popup_ref);
6610
0
        window->PopupId = popup_ref.PopupId;
6611
0
    }
6612
6613
    // Process SetNextWindow***() calls
6614
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6615
440k
    bool window_pos_set_by_api = false;
6616
440k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6617
440k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6618
0
    {
6619
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6620
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6621
0
        {
6622
            // May be processed on the next frame if this is our first frame and we are measuring size
6623
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6624
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6625
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6626
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6627
0
        }
6628
0
        else
6629
0
        {
6630
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6631
0
        }
6632
0
    }
6633
440k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6634
270k
    {
6635
270k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6636
270k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6637
270k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6638
270k
    }
6639
440k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6640
0
    {
6641
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6642
0
        {
6643
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6644
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6645
0
        }
6646
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6647
0
        {
6648
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6649
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6650
0
        }
6651
0
    }
6652
440k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6653
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6654
440k
    else if (first_begin_of_the_frame)
6655
440k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6656
440k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6657
0
        window->WindowClass = g.NextWindowData.WindowClass;
6658
440k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6659
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6660
440k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6661
0
        FocusWindow(window);
6662
440k
    if (window->Appearing)
6663
1.98k
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6664
6665
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6666
440k
    if (first_begin_of_the_frame)
6667
440k
    {
6668
        // Initialize
6669
440k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6670
440k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6671
440k
        window->Active = true;
6672
440k
        window->HasCloseButton = (p_open != NULL);
6673
440k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6674
440k
        window->IDStack.resize(1);
6675
440k
        window->DrawList->_ResetForNewFrame();
6676
440k
        window->DC.CurrentTableIdx = -1;
6677
440k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6678
0
        {
6679
0
            window->DrawList->ChannelsSplit(2);
6680
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6681
0
        }
6682
6683
        // Restore buffer capacity when woken from a compacted state, to avoid
6684
440k
        if (window->MemoryCompacted)
6685
0
            GcAwakeTransientWindowBuffers(window);
6686
6687
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6688
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6689
440k
        bool window_title_visible_elsewhere = false;
6690
440k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6691
0
            window_title_visible_elsewhere = true;
6692
440k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6693
0
            window_title_visible_elsewhere = true;
6694
440k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6695
0
        {
6696
0
            size_t buf_len = (size_t)window->NameBufLen;
6697
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6698
0
            window->NameBufLen = (int)buf_len;
6699
0
        }
6700
6701
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6702
6703
        // Update contents size from last frame for auto-fitting (or use explicit size)
6704
440k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6705
6706
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6707
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6708
        // it has a single usage before this code block and may be set below before it is finally checked.
6709
440k
        if (window->HiddenFramesCanSkipItems > 0)
6710
8.89k
            window->HiddenFramesCanSkipItems--;
6711
440k
        if (window->HiddenFramesCannotSkipItems > 0)
6712
1.97k
            window->HiddenFramesCannotSkipItems--;
6713
440k
        if (window->HiddenFramesForRenderOnly > 0)
6714
0
            window->HiddenFramesForRenderOnly--;
6715
6716
        // Hide new windows for one frame until they calculate their size
6717
440k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6718
4
            window->HiddenFramesCannotSkipItems = 1;
6719
6720
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6721
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6722
440k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6723
1.96k
        {
6724
1.96k
            window->HiddenFramesCannotSkipItems = 1;
6725
1.96k
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6726
1.96k
            {
6727
1.96k
                if (!window_size_x_set_by_api)
6728
1.96k
                    window->Size.x = window->SizeFull.x = 0.f;
6729
1.96k
                if (!window_size_y_set_by_api)
6730
1.96k
                    window->Size.y = window->SizeFull.y = 0.f;
6731
1.96k
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6732
1.96k
            }
6733
1.96k
        }
6734
6735
        // SELECT VIEWPORT
6736
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6737
6738
440k
        WindowSelectViewport(window);
6739
440k
        SetCurrentViewport(window, window->Viewport);
6740
440k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6741
440k
        SetCurrentWindow(window);
6742
440k
        flags = window->Flags;
6743
6744
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6745
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
6746
6747
440k
        if (flags & ImGuiWindowFlags_ChildWindow)
6748
103k
            window->WindowBorderSize = style.ChildBorderSize;
6749
336k
        else
6750
336k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6751
440k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
6752
58.4k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
6753
381k
        else
6754
381k
            window->WindowPadding = style.WindowPadding;
6755
6756
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
6757
440k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
6758
440k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
6759
6760
440k
        bool use_current_size_for_scrollbar_x = window_just_created;
6761
440k
        bool use_current_size_for_scrollbar_y = window_just_created;
6762
6763
        // Collapse window by double-clicking on title bar
6764
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
6765
440k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
6766
334k
        {
6767
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
6768
334k
            ImRect title_bar_rect = window->TitleBarRect();
6769
334k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
6770
9
                window->WantCollapseToggle = true;
6771
334k
            if (window->WantCollapseToggle)
6772
9
            {
6773
9
                window->Collapsed = !window->Collapsed;
6774
9
                if (!window->Collapsed)
6775
4
                    use_current_size_for_scrollbar_y = true;
6776
9
                MarkIniSettingsDirty(window);
6777
9
            }
6778
334k
        }
6779
105k
        else
6780
105k
        {
6781
105k
            window->Collapsed = false;
6782
105k
        }
6783
440k
        window->WantCollapseToggle = false;
6784
6785
        // SIZE
6786
6787
        // Outer Decoration Sizes
6788
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
6789
440k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
6790
440k
        window->DecoOuterSizeX1 = 0.0f;
6791
440k
        window->DecoOuterSizeX2 = 0.0f;
6792
440k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
6793
440k
        window->DecoOuterSizeY2 = 0.0f;
6794
440k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
6795
6796
        // Calculate auto-fit size, handle automatic resize
6797
440k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
6798
440k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
6799
2.36k
        {
6800
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
6801
2.36k
            if (!window_size_x_set_by_api)
6802
2.36k
            {
6803
2.36k
                window->SizeFull.x = size_auto_fit.x;
6804
2.36k
                use_current_size_for_scrollbar_x = true;
6805
2.36k
            }
6806
2.36k
            if (!window_size_y_set_by_api)
6807
2.36k
            {
6808
2.36k
                window->SizeFull.y = size_auto_fit.y;
6809
2.36k
                use_current_size_for_scrollbar_y = true;
6810
2.36k
            }
6811
2.36k
        }
6812
437k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6813
6
        {
6814
            // Auto-fit may only grow window during the first few frames
6815
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
6816
6
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
6817
6
            {
6818
6
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
6819
6
                use_current_size_for_scrollbar_x = true;
6820
6
            }
6821
6
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
6822
6
            {
6823
6
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
6824
6
                use_current_size_for_scrollbar_y = true;
6825
6
            }
6826
6
            if (!window->Collapsed)
6827
6
                MarkIniSettingsDirty(window);
6828
6
        }
6829
6830
        // Apply minimum/maximum window size constraints and final size
6831
440k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
6832
440k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
6833
6834
        // POSITION
6835
6836
        // Popup latch its initial position, will position itself when it appears next frame
6837
440k
        if (window_just_activated_by_user)
6838
1.98k
        {
6839
1.98k
            window->AutoPosLastDirection = ImGuiDir_None;
6840
1.98k
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
6841
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
6842
1.98k
        }
6843
6844
        // Position child window
6845
440k
        if (flags & ImGuiWindowFlags_ChildWindow)
6846
103k
        {
6847
103k
            IM_ASSERT(parent_window && parent_window->Active);
6848
103k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
6849
103k
            parent_window->DC.ChildWindows.push_back(window);
6850
103k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
6851
103k
                window->Pos = parent_window->DC.CursorPos;
6852
103k
        }
6853
6854
440k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
6855
440k
        if (window_pos_with_pivot)
6856
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
6857
440k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
6858
0
            window->Pos = FindBestWindowPosForPopup(window);
6859
440k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
6860
0
            window->Pos = FindBestWindowPosForPopup(window);
6861
440k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
6862
2.36k
            window->Pos = FindBestWindowPosForPopup(window);
6863
6864
        // Late create viewport if we don't fit within our current host viewport.
6865
440k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
6866
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
6867
0
            {
6868
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
6869
                //ImGuiViewport* old_viewport = window->Viewport;
6870
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
6871
6872
                // FIXME-DPI
6873
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
6874
0
                SetCurrentViewport(window, window->Viewport);
6875
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6876
0
                SetCurrentWindow(window);
6877
0
            }
6878
6879
440k
        if (window->ViewportOwned)
6880
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
6881
6882
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
6883
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
6884
440k
        ImRect viewport_rect(window->Viewport->GetMainRect());
6885
440k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
6886
440k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
6887
440k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
6888
6889
        // Clamp position/size so window stays visible within its viewport or monitor
6890
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
6891
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
6892
440k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
6893
336k
        {
6894
336k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
6895
336k
            {
6896
336k
                ClampWindowPos(window, visibility_rect);
6897
336k
            }
6898
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
6899
0
            {
6900
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
6901
0
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
6902
0
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
6903
0
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
6904
0
                ClampWindowPos(window, visibility_rect);
6905
0
            }
6906
336k
        }
6907
440k
        window->Pos = ImFloor(window->Pos);
6908
6909
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
6910
        // Large values tend to lead to variety of artifacts and are not recommended.
6911
440k
        if (window->ViewportOwned || window->DockIsActive)
6912
0
            window->WindowRounding = 0.0f;
6913
440k
        else
6914
440k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
6915
6916
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
6917
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6918
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
6919
6920
        // Apply window focus (new and reactivated windows are moved to front)
6921
440k
        bool want_focus = false;
6922
440k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
6923
1.98k
        {
6924
1.98k
            if (flags & ImGuiWindowFlags_Popup)
6925
0
                want_focus = true;
6926
1.98k
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
6927
6
                want_focus = true;
6928
1.98k
        }
6929
6930
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
6931
#ifdef IMGUI_ENABLE_TEST_ENGINE
6932
        if (g.TestEngineHookItems)
6933
        {
6934
            IM_ASSERT(window->IDStack.Size == 1);
6935
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
6936
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
6937
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
6938
            window->IDStack.Size = 1;
6939
        }
6940
#endif
6941
6942
        // Decide if we are going to handle borders and resize grips
6943
440k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
6944
6945
        // Handle manual resize: Resize Grips, Borders, Gamepad
6946
440k
        int border_held = -1;
6947
440k
        ImU32 resize_grip_col[4] = {};
6948
440k
        const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
6949
440k
        const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6950
440k
        if (handle_borders_and_resize_grips && !window->Collapsed)
6951
376k
            if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
6952
6
                use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
6953
440k
        window->ResizeBorderHeld = (signed char)border_held;
6954
6955
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
6956
440k
        if (window->ViewportOwned)
6957
0
        {
6958
0
            if (!window->Viewport->PlatformRequestMove)
6959
0
                window->Viewport->Pos = window->Pos;
6960
0
            if (!window->Viewport->PlatformRequestResize)
6961
0
                window->Viewport->Size = window->Size;
6962
0
            window->Viewport->UpdateWorkRect();
6963
0
            viewport_rect = window->Viewport->GetMainRect();
6964
0
        }
6965
6966
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
6967
440k
        window->ViewportPos = window->Viewport->Pos;
6968
6969
        // SCROLLBAR VISIBILITY
6970
6971
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
6972
440k
        if (!window->Collapsed)
6973
376k
        {
6974
            // When reading the current size we need to read it after size constraints have been applied.
6975
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
6976
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
6977
376k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
6978
376k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
6979
376k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
6980
376k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
6981
376k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
6982
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
6983
376k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
6984
376k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
6985
376k
            if (window->ScrollbarX && !window->ScrollbarY)
6986
91.6k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
6987
376k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
6988
6989
            // Amend the partially filled window->DecorationXXX values.
6990
376k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
6991
376k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
6992
376k
        }
6993
6994
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
6995
        // Update various regions. Variables they depend on should be set above in this function.
6996
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
6997
6998
        // Outer rectangle
6999
        // Not affected by window border size. Used by:
7000
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7001
        // - Begin() initial clipping rect for drawing window background and borders.
7002
        // - Begin() clipping whole child
7003
440k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7004
440k
        const ImRect outer_rect = window->Rect();
7005
440k
        const ImRect title_bar_rect = window->TitleBarRect();
7006
440k
        window->OuterRectClipped = outer_rect;
7007
440k
        if (window->DockIsActive)
7008
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
7009
440k
        window->OuterRectClipped.ClipWith(host_rect);
7010
7011
        // Inner rectangle
7012
        // Not affected by window border size. Used by:
7013
        // - InnerClipRect
7014
        // - ScrollToRectEx()
7015
        // - NavUpdatePageUpPageDown()
7016
        // - Scrollbar()
7017
440k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7018
440k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7019
440k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7020
440k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7021
7022
        // Inner clipping rectangle.
7023
        // Will extend a little bit outside the normal work region.
7024
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7025
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7026
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7027
        // Affected by window/frame border size. Used by:
7028
        // - Begin() initial clip rect
7029
440k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7030
440k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7031
440k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7032
440k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7033
440k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7034
440k
        window->InnerClipRect.ClipWithFull(host_rect);
7035
7036
        // Default item width. Make it proportional to window size if window manually resizes
7037
440k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7038
437k
            window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
7039
2.36k
        else
7040
2.36k
            window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
7041
7042
        // SCROLLING
7043
7044
        // Lock down maximum scrolling
7045
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7046
        // for right/bottom aligned items without creating a scrollbar.
7047
440k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7048
440k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7049
7050
        // Apply scrolling
7051
440k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7052
440k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7053
440k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7054
7055
        // DRAWING
7056
7057
        // Setup draw list and outer clipping rectangle
7058
440k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7059
440k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7060
440k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7061
7062
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7063
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7064
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7065
440k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7066
440k
        if (is_undocked_or_docked_visible)
7067
440k
        {
7068
440k
            bool render_decorations_in_parent = false;
7069
440k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7070
103k
            {
7071
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7072
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7073
103k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7074
103k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7075
103k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7076
103k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7077
103k
                    render_decorations_in_parent = true;
7078
103k
            }
7079
440k
            if (render_decorations_in_parent)
7080
103k
                window->DrawList = parent_window->DrawList;
7081
7082
            // Handle title bar, scrollbar, resize grips and resize borders
7083
440k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7084
440k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7085
440k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7086
7087
440k
            if (render_decorations_in_parent)
7088
103k
                window->DrawList = &window->DrawListInst;
7089
440k
        }
7090
7091
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7092
7093
        // Work rectangle.
7094
        // Affected by window padding and border size. Used by:
7095
        // - Columns() for right-most edge
7096
        // - TreeNode(), CollapsingHeader() for right-most edge
7097
        // - BeginTabBar() for right-most edge
7098
440k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7099
440k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7100
440k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7101
440k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7102
440k
        window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7103
440k
        window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7104
440k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7105
440k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7106
440k
        window->ParentWorkRect = window->WorkRect;
7107
7108
        // [LEGACY] Content Region
7109
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7110
        // Used by:
7111
        // - Mouse wheel scrolling + many other things
7112
440k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7113
440k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7114
440k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7115
440k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7116
7117
        // Setup drawing context
7118
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7119
440k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7120
440k
        window->DC.GroupOffset.x = 0.0f;
7121
440k
        window->DC.ColumnsOffset.x = 0.0f;
7122
7123
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7124
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7125
440k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7126
440k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7127
440k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7128
440k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7129
440k
        window->DC.CursorPos = window->DC.CursorStartPos;
7130
440k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7131
440k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7132
440k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7133
440k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7134
440k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7135
440k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7136
7137
440k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7138
440k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7139
440k
        window->DC.NavLayersActiveMaskNext = 0x00;
7140
440k
        window->DC.NavIsScrollPushableX = true;
7141
440k
        window->DC.NavHideHighlightOneFrame = false;
7142
440k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7143
7144
440k
        window->DC.MenuBarAppending = false;
7145
440k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7146
440k
        window->DC.TreeDepth = 0;
7147
440k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7148
440k
        window->DC.ChildWindows.resize(0);
7149
440k
        window->DC.StateStorage = &window->StateStorage;
7150
440k
        window->DC.CurrentColumns = NULL;
7151
440k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7152
440k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7153
7154
440k
        window->DC.ItemWidth = window->ItemWidthDefault;
7155
440k
        window->DC.TextWrapPos = -1.0f; // disabled
7156
440k
        window->DC.ItemWidthStack.resize(0);
7157
440k
        window->DC.TextWrapPosStack.resize(0);
7158
7159
440k
        if (window->AutoFitFramesX > 0)
7160
8
            window->AutoFitFramesX--;
7161
440k
        if (window->AutoFitFramesY > 0)
7162
8
            window->AutoFitFramesY--;
7163
7164
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7165
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7166
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7167
        // - Position window behind the modal that is not a begin-parent of this window.
7168
440k
        if (want_focus)
7169
6
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7170
440k
        if (want_focus && window == g.NavWindow)
7171
6
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7172
7173
        // Close requested by platform window
7174
440k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7175
0
        {
7176
0
            if (!window->DockIsActive || window->DockTabIsVisible)
7177
0
            {
7178
0
                window->Viewport->PlatformRequestClose = false;
7179
0
                g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue.
7180
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' PlatformRequestClose\n", window->Name);
7181
0
                *p_open = false;
7182
0
            }
7183
0
        }
7184
7185
        // Title bar
7186
440k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7187
334k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7188
7189
        // Clear hit test shape every frame
7190
440k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7191
7192
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7193
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7194
        // Maybe we can support CTRL+C on every element?
7195
        /*
7196
        //if (g.NavWindow == window && g.ActiveId == 0)
7197
        if (g.ActiveId == window->MoveId)
7198
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7199
                LogToClipboard();
7200
        */
7201
7202
440k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7203
440k
        {
7204
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7205
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7206
440k
            if ((g.MovingWindow == window) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift))
7207
185
                if ((window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7208
185
                    BeginDockableDragDropSource(window);
7209
7210
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7211
440k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7212
45
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7213
27
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7214
27
                        BeginDockableDragDropTarget(window);
7215
440k
        }
7216
7217
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7218
        // This is useful to allow creating context menus on title bar only, etc.
7219
440k
        if (window->DockIsActive)
7220
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7221
440k
        else
7222
440k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7223
7224
        // [DEBUG]
7225
440k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7226
440k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7227
0
            DebugLocateItemResolveWithLastItem();
7228
440k
#endif
7229
7230
        // [Test Engine] Register title bar / tab with MoveId.
7231
#ifdef IMGUI_ENABLE_TEST_ENGINE
7232
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7233
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7234
#endif
7235
440k
    }
7236
0
    else
7237
0
    {
7238
        // Append
7239
0
        SetCurrentViewport(window, window->Viewport);
7240
0
        SetCurrentWindow(window);
7241
0
    }
7242
7243
440k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7244
440k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7245
7246
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7247
440k
    window->WriteAccessed = false;
7248
440k
    window->BeginCount++;
7249
440k
    g.NextWindowData.ClearFlags();
7250
7251
    // Update visibility
7252
440k
    if (first_begin_of_the_frame)
7253
440k
    {
7254
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7255
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7256
        // This is analogous to regular windows being hidden from one frame.
7257
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7258
440k
        if (window->DockIsActive && !window->DockTabIsVisible)
7259
0
        {
7260
0
            if (window->LastFrameJustFocused == g.FrameCount)
7261
0
                window->HiddenFramesCannotSkipItems = 1;
7262
0
            else
7263
0
                window->HiddenFramesCanSkipItems = 1;
7264
0
        }
7265
7266
440k
        if (flags & ImGuiWindowFlags_ChildWindow)
7267
103k
        {
7268
            // Child window can be out of sight and have "negative" clip windows.
7269
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7270
103k
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
7271
103k
            if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
7272
103k
            {
7273
103k
                const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7274
103k
                if (!g.LogEnabled && !nav_request)
7275
103k
                    if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7276
8.89k
                        window->HiddenFramesCanSkipItems = 1;
7277
103k
            }
7278
7279
            // Hide along with parent or if parent is collapsed
7280
103k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7281
0
                window->HiddenFramesCanSkipItems = 1;
7282
103k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7283
3
                window->HiddenFramesCannotSkipItems = 1;
7284
103k
        }
7285
7286
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7287
440k
        if (style.Alpha <= 0.0f)
7288
0
            window->HiddenFramesCanSkipItems = 1;
7289
7290
        // Update the Hidden flag
7291
440k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7292
440k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7293
7294
        // Disable inputs for requested number of frames
7295
440k
        if (window->DisableInputsFrames > 0)
7296
0
        {
7297
0
            window->DisableInputsFrames--;
7298
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7299
0
        }
7300
7301
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7302
440k
        bool skip_items = false;
7303
440k
        if (window->Collapsed || !window->Active || hidden_regular)
7304
74.4k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7305
72.5k
                skip_items = true;
7306
440k
        window->SkipItems = skip_items;
7307
7308
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7309
440k
        if (window->SkipItems)
7310
72.5k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7311
7312
        // Sanity check: there are two spots which can set Appearing = true
7313
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7314
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7315
440k
        if (window->SkipItems && !window->Appearing)
7316
440k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7317
440k
    }
7318
7319
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7320
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7321
440k
    if (!window->IsFallbackWindow && ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size)))
7322
0
    {
7323
0
        if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7324
0
        if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7325
0
        return false;
7326
0
    }
7327
7328
440k
    return !window->SkipItems;
7329
440k
}
7330
7331
void ImGui::End()
7332
440k
{
7333
440k
    ImGuiContext& g = *GImGui;
7334
440k
    ImGuiWindow* window = g.CurrentWindow;
7335
7336
    // Error checking: verify that user hasn't called End() too many times!
7337
440k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7338
0
    {
7339
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7340
0
        return;
7341
0
    }
7342
440k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7343
7344
    // Error checking: verify that user doesn't directly call End() on a child window.
7345
440k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7346
440k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7347
7348
    // Close anything that is open
7349
440k
    if (window->DC.CurrentColumns)
7350
0
        EndColumns();
7351
440k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7352
440k
        PopClipRect();
7353
440k
    PopFocusScope();
7354
7355
    // Stop logging
7356
440k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7357
336k
        LogFinish();
7358
7359
440k
    if (window->DC.IsSetPos)
7360
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7361
7362
    // Docking: report contents sizes to parent to allow for auto-resize
7363
440k
    if (window->DockNode && window->DockTabIsVisible)
7364
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7365
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7366
7367
    // Pop from window stack
7368
440k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7369
440k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7370
0
        g.BeginMenuCount--;
7371
440k
    if (window->Flags & ImGuiWindowFlags_Popup)
7372
0
        g.BeginPopupStack.pop_back();
7373
440k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(&g);
7374
440k
    g.CurrentWindowStack.pop_back();
7375
440k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7376
440k
    if (g.CurrentWindow)
7377
272k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7378
440k
}
7379
7380
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7381
45.8k
{
7382
45.8k
    ImGuiContext& g = *GImGui;
7383
45.8k
    IM_ASSERT(window == window->RootWindow);
7384
7385
45.8k
    const int cur_order = window->FocusOrder;
7386
45.8k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7387
45.8k
    if (g.WindowsFocusOrder.back() == window)
7388
45.8k
        return;
7389
7390
1
    const int new_order = g.WindowsFocusOrder.Size - 1;
7391
2
    for (int n = cur_order; n < new_order; n++)
7392
1
    {
7393
1
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7394
1
        g.WindowsFocusOrder[n]->FocusOrder--;
7395
1
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7396
1
    }
7397
1
    g.WindowsFocusOrder[new_order] = window;
7398
1
    window->FocusOrder = (short)new_order;
7399
1
}
7400
7401
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7402
45.8k
{
7403
45.8k
    ImGuiContext& g = *GImGui;
7404
45.8k
    ImGuiWindow* current_front_window = g.Windows.back();
7405
45.8k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7406
45.8k
        return;
7407
2
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7408
2
        if (g.Windows[i] == window)
7409
1
        {
7410
1
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7411
1
            g.Windows[g.Windows.Size - 1] = window;
7412
1
            break;
7413
1
        }
7414
1
}
7415
7416
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7417
0
{
7418
0
    ImGuiContext& g = *GImGui;
7419
0
    if (g.Windows[0] == window)
7420
0
        return;
7421
0
    for (int i = 0; i < g.Windows.Size; i++)
7422
0
        if (g.Windows[i] == window)
7423
0
        {
7424
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7425
0
            g.Windows[0] = window;
7426
0
            break;
7427
0
        }
7428
0
}
7429
7430
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7431
0
{
7432
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7433
0
    ImGuiContext& g = *GImGui;
7434
0
    window = window->RootWindow;
7435
0
    behind_window = behind_window->RootWindow;
7436
0
    int pos_wnd = FindWindowDisplayIndex(window);
7437
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7438
0
    if (pos_wnd < pos_beh)
7439
0
    {
7440
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7441
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7442
0
        g.Windows[pos_beh - 1] = window;
7443
0
    }
7444
0
    else
7445
0
    {
7446
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7447
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7448
0
        g.Windows[pos_beh] = window;
7449
0
    }
7450
0
}
7451
7452
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7453
0
{
7454
0
    ImGuiContext& g = *GImGui;
7455
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7456
0
}
7457
7458
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7459
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7460
70.9k
{
7461
70.9k
    ImGuiContext& g = *GImGui;
7462
7463
    // Modal check?
7464
70.9k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7465
727
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7466
0
        {
7467
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7468
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7469
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring to right below modal.
7470
0
            return;
7471
0
        }
7472
7473
    // Find last focused child (if any) and focus it instead.
7474
70.9k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7475
0
        window = NavRestoreLastChildNavWindow(window);
7476
7477
    // Apply focus
7478
70.9k
    if (g.NavWindow != window)
7479
23.1k
    {
7480
23.1k
        SetNavWindow(window);
7481
23.1k
        if (window && g.NavDisableMouseHover)
7482
1.81k
            g.NavMousePosDirty = true;
7483
23.1k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7484
23.1k
        g.NavLayer = ImGuiNavLayer_Main;
7485
23.1k
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7486
23.1k
        g.NavIdIsAlive = false;
7487
7488
        // Close popups if any
7489
23.1k
        ClosePopupsOverWindow(window, false);
7490
23.1k
    }
7491
7492
    // Move the root window to the top of the pile
7493
70.9k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7494
70.9k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7495
70.9k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7496
70.9k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7497
70.9k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7498
7499
    // Steal active widgets. Some of the cases it triggers includes:
7500
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7501
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7502
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7503
70.9k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7504
947
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7505
30
            ClearActiveID();
7506
7507
    // Passing NULL allow to disable keyboard focus
7508
70.9k
    if (!window)
7509
25.0k
        return;
7510
45.8k
    window->LastFrameJustFocused = g.FrameCount;
7511
7512
    // Select in dock node
7513
45.8k
    if (dock_node && dock_node->TabBar)
7514
0
        dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7515
7516
    // Bring to front
7517
45.8k
    BringWindowToFocusFront(focus_front_window);
7518
45.8k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7519
45.8k
        BringWindowToDisplayFront(display_front_window);
7520
45.8k
}
7521
7522
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7523
0
{
7524
0
    ImGuiContext& g = *GImGui;
7525
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
7526
0
    if (under_this_window != NULL)
7527
0
    {
7528
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7529
0
        int offset = -1;
7530
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7531
0
        {
7532
0
            under_this_window = under_this_window->ParentWindow;
7533
0
            offset = 0;
7534
0
        }
7535
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7536
0
    }
7537
0
    for (int i = start_idx; i >= 0; i--)
7538
0
    {
7539
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7540
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7541
0
        IM_ASSERT(window == window->RootWindow);
7542
0
        if (window == ignore_window || !window->WasActive)
7543
0
            continue;
7544
0
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
7545
0
            continue;
7546
0
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7547
0
        {
7548
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
7549
            // This is failing (lagging by one frame) for docked windows.
7550
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7551
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7552
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7553
0
            FocusWindow(window, flags);
7554
0
            return;
7555
0
        }
7556
0
    }
7557
0
    FocusWindow(NULL, flags);
7558
0
}
7559
7560
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7561
void ImGui::SetCurrentFont(ImFont* font)
7562
167k
{
7563
167k
    ImGuiContext& g = *GImGui;
7564
167k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7565
167k
    IM_ASSERT(font->Scale > 0.0f);
7566
167k
    g.Font = font;
7567
167k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7568
167k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7569
7570
167k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7571
167k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7572
167k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7573
167k
    g.DrawListSharedData.Font = g.Font;
7574
167k
    g.DrawListSharedData.FontSize = g.FontSize;
7575
167k
}
7576
7577
void ImGui::PushFont(ImFont* font)
7578
0
{
7579
0
    ImGuiContext& g = *GImGui;
7580
0
    if (!font)
7581
0
        font = GetDefaultFont();
7582
0
    SetCurrentFont(font);
7583
0
    g.FontStack.push_back(font);
7584
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7585
0
}
7586
7587
void  ImGui::PopFont()
7588
0
{
7589
0
    ImGuiContext& g = *GImGui;
7590
0
    g.CurrentWindow->DrawList->PopTextureID();
7591
0
    g.FontStack.pop_back();
7592
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7593
0
}
7594
7595
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7596
103k
{
7597
103k
    ImGuiContext& g = *GImGui;
7598
103k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7599
103k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7600
103k
    if (enabled)
7601
0
        item_flags |= option;
7602
103k
    else
7603
103k
        item_flags &= ~option;
7604
103k
    g.CurrentItemFlags = item_flags;
7605
103k
    g.ItemFlagsStack.push_back(item_flags);
7606
103k
}
7607
7608
void ImGui::PopItemFlag()
7609
103k
{
7610
103k
    ImGuiContext& g = *GImGui;
7611
103k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7612
103k
    g.ItemFlagsStack.pop_back();
7613
103k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7614
103k
}
7615
7616
// BeginDisabled()/EndDisabled()
7617
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7618
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7619
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7620
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7621
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7622
void ImGui::BeginDisabled(bool disabled)
7623
0
{
7624
0
    ImGuiContext& g = *GImGui;
7625
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7626
0
    if (!was_disabled && disabled)
7627
0
    {
7628
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7629
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7630
0
    }
7631
0
    if (was_disabled || disabled)
7632
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7633
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7634
0
    g.DisabledStackSize++;
7635
0
}
7636
7637
void ImGui::EndDisabled()
7638
0
{
7639
0
    ImGuiContext& g = *GImGui;
7640
0
    IM_ASSERT(g.DisabledStackSize > 0);
7641
0
    g.DisabledStackSize--;
7642
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7643
    //PopItemFlag();
7644
0
    g.ItemFlagsStack.pop_back();
7645
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7646
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7647
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7648
0
}
7649
7650
void ImGui::PushTabStop(bool tab_stop)
7651
103k
{
7652
103k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
7653
103k
}
7654
7655
void ImGui::PopTabStop()
7656
103k
{
7657
103k
    PopItemFlag();
7658
103k
}
7659
7660
void ImGui::PushButtonRepeat(bool repeat)
7661
0
{
7662
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7663
0
}
7664
7665
void ImGui::PopButtonRepeat()
7666
0
{
7667
0
    PopItemFlag();
7668
0
}
7669
7670
void ImGui::PushTextWrapPos(float wrap_pos_x)
7671
0
{
7672
0
    ImGuiWindow* window = GetCurrentWindow();
7673
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7674
0
    window->DC.TextWrapPos = wrap_pos_x;
7675
0
}
7676
7677
void ImGui::PopTextWrapPos()
7678
0
{
7679
0
    ImGuiWindow* window = GetCurrentWindow();
7680
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7681
0
    window->DC.TextWrapPosStack.pop_back();
7682
0
}
7683
7684
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7685
0
{
7686
0
    ImGuiWindow* last_window = NULL;
7687
0
    while (last_window != window)
7688
0
    {
7689
0
        last_window = window;
7690
0
        window = window->RootWindow;
7691
0
        if (popup_hierarchy)
7692
0
            window = window->RootWindowPopupTree;
7693
0
    if (dock_hierarchy)
7694
0
      window = window->RootWindowDockTree;
7695
0
  }
7696
0
    return window;
7697
0
}
7698
7699
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7700
0
{
7701
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7702
0
    if (window_root == potential_parent)
7703
0
        return true;
7704
0
    while (window != NULL)
7705
0
    {
7706
0
        if (window == potential_parent)
7707
0
            return true;
7708
0
        if (window == window_root) // end of chain
7709
0
            return false;
7710
0
        window = window->ParentWindow;
7711
0
    }
7712
0
    return false;
7713
0
}
7714
7715
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7716
0
{
7717
0
    if (window->RootWindow == potential_parent)
7718
0
        return true;
7719
0
    while (window != NULL)
7720
0
    {
7721
0
        if (window == potential_parent)
7722
0
            return true;
7723
0
        window = window->ParentWindowInBeginStack;
7724
0
    }
7725
0
    return false;
7726
0
}
7727
7728
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7729
0
{
7730
0
    ImGuiContext& g = *GImGui;
7731
7732
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7733
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
7734
0
    if (display_layer_delta != 0)
7735
0
        return display_layer_delta > 0;
7736
7737
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
7738
0
    {
7739
0
        ImGuiWindow* candidate_window = g.Windows[i];
7740
0
        if (candidate_window == potential_above)
7741
0
            return true;
7742
0
        if (candidate_window == potential_below)
7743
0
            return false;
7744
0
    }
7745
0
    return false;
7746
0
}
7747
7748
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7749
173k
{
7750
173k
    IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0);   // Flags not supported by this function
7751
173k
    ImGuiContext& g = *GImGui;
7752
173k
    ImGuiWindow* ref_window = g.HoveredWindow;
7753
173k
    ImGuiWindow* cur_window = g.CurrentWindow;
7754
173k
    if (ref_window == NULL)
7755
133k
        return false;
7756
7757
40.4k
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
7758
40.4k
    {
7759
40.4k
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
7760
40.4k
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
7761
40.4k
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
7762
40.4k
        if (flags & ImGuiHoveredFlags_RootWindow)
7763
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7764
7765
40.4k
        bool result;
7766
40.4k
        if (flags & ImGuiHoveredFlags_ChildWindows)
7767
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7768
40.4k
        else
7769
40.4k
            result = (ref_window == cur_window);
7770
40.4k
        if (!result)
7771
2.55k
            return false;
7772
40.4k
    }
7773
7774
37.8k
    if (!IsWindowContentHoverable(ref_window, flags))
7775
0
        return false;
7776
37.8k
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
7777
37.8k
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
7778
55
            return false;
7779
37.8k
    return true;
7780
37.8k
}
7781
7782
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
7783
203k
{
7784
203k
    ImGuiContext& g = *GImGui;
7785
203k
    ImGuiWindow* ref_window = g.NavWindow;
7786
203k
    ImGuiWindow* cur_window = g.CurrentWindow;
7787
7788
203k
    if (ref_window == NULL)
7789
50.7k
        return false;
7790
153k
    if (flags & ImGuiFocusedFlags_AnyWindow)
7791
0
        return true;
7792
7793
153k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
7794
153k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
7795
153k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
7796
153k
    if (flags & ImGuiHoveredFlags_RootWindow)
7797
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7798
7799
153k
    if (flags & ImGuiHoveredFlags_ChildWindows)
7800
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7801
153k
    else
7802
153k
        return (ref_window == cur_window);
7803
153k
}
7804
7805
ImGuiID ImGui::GetWindowDockID()
7806
0
{
7807
0
    ImGuiContext& g = *GImGui;
7808
0
    return g.CurrentWindow->DockId;
7809
0
}
7810
7811
bool ImGui::IsWindowDocked()
7812
0
{
7813
0
    ImGuiContext& g = *GImGui;
7814
0
    return g.CurrentWindow->DockIsActive;
7815
0
}
7816
7817
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
7818
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
7819
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
7820
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
7821
0
{
7822
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
7823
0
}
7824
7825
float ImGui::GetWindowWidth()
7826
43.7k
{
7827
43.7k
    ImGuiWindow* window = GImGui->CurrentWindow;
7828
43.7k
    return window->Size.x;
7829
43.7k
}
7830
7831
float ImGui::GetWindowHeight()
7832
45.3k
{
7833
45.3k
    ImGuiWindow* window = GImGui->CurrentWindow;
7834
45.3k
    return window->Size.y;
7835
45.3k
}
7836
7837
ImVec2 ImGui::GetWindowPos()
7838
0
{
7839
0
    ImGuiContext& g = *GImGui;
7840
0
    ImGuiWindow* window = g.CurrentWindow;
7841
0
    return window->Pos;
7842
0
}
7843
7844
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
7845
55
{
7846
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7847
55
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
7848
0
        return;
7849
7850
55
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7851
55
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7852
55
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
7853
7854
    // Set
7855
55
    const ImVec2 old_pos = window->Pos;
7856
55
    window->Pos = ImFloor(pos);
7857
55
    ImVec2 offset = window->Pos - old_pos;
7858
55
    if (offset.x == 0.0f && offset.y == 0.0f)
7859
0
        return;
7860
55
    MarkIniSettingsDirty(window);
7861
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
7862
55
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
7863
55
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
7864
55
    window->DC.IdealMaxPos += offset;
7865
55
    window->DC.CursorStartPos += offset;
7866
55
}
7867
7868
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
7869
0
{
7870
0
    ImGuiWindow* window = GetCurrentWindowRead();
7871
0
    SetWindowPos(window, pos, cond);
7872
0
}
7873
7874
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
7875
0
{
7876
0
    if (ImGuiWindow* window = FindWindowByName(name))
7877
0
        SetWindowPos(window, pos, cond);
7878
0
}
7879
7880
ImVec2 ImGui::GetWindowSize()
7881
0
{
7882
0
    ImGuiWindow* window = GetCurrentWindowRead();
7883
0
    return window->Size;
7884
0
}
7885
7886
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
7887
270k
{
7888
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7889
270k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
7890
167k
        return;
7891
7892
103k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7893
103k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7894
7895
    // Set
7896
103k
    ImVec2 old_size = window->SizeFull;
7897
103k
    window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
7898
103k
    window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
7899
103k
    if (size.x <= 0.0f)
7900
0
        window->AutoFitOnlyGrows = false;
7901
103k
    else
7902
103k
        window->SizeFull.x = IM_FLOOR(size.x);
7903
103k
    if (size.y <= 0.0f)
7904
0
        window->AutoFitOnlyGrows = false;
7905
103k
    else
7906
103k
        window->SizeFull.y = IM_FLOOR(size.y);
7907
103k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
7908
19.5k
        MarkIniSettingsDirty(window);
7909
103k
}
7910
7911
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
7912
0
{
7913
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
7914
0
}
7915
7916
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
7917
0
{
7918
0
    if (ImGuiWindow* window = FindWindowByName(name))
7919
0
        SetWindowSize(window, size, cond);
7920
0
}
7921
7922
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
7923
0
{
7924
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7925
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
7926
0
        return;
7927
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7928
7929
    // Set
7930
0
    window->Collapsed = collapsed;
7931
0
}
7932
7933
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
7934
0
{
7935
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
7936
0
    window->HitTestHoleSize = ImVec2ih(size);
7937
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
7938
0
}
7939
7940
void ImGui::SetWindowHiddendAndSkipItemsForCurrentFrame(ImGuiWindow* window)
7941
0
{
7942
0
    window->Hidden = window->SkipItems = true;
7943
0
    window->HiddenFramesCanSkipItems = 1;
7944
0
}
7945
7946
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
7947
0
{
7948
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
7949
0
}
7950
7951
bool ImGui::IsWindowCollapsed()
7952
0
{
7953
0
    ImGuiWindow* window = GetCurrentWindowRead();
7954
0
    return window->Collapsed;
7955
0
}
7956
7957
bool ImGui::IsWindowAppearing()
7958
0
{
7959
0
    ImGuiWindow* window = GetCurrentWindowRead();
7960
0
    return window->Appearing;
7961
0
}
7962
7963
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
7964
0
{
7965
0
    if (ImGuiWindow* window = FindWindowByName(name))
7966
0
        SetWindowCollapsed(window, collapsed, cond);
7967
0
}
7968
7969
void ImGui::SetWindowFocus()
7970
43.7k
{
7971
43.7k
    FocusWindow(GImGui->CurrentWindow);
7972
43.7k
}
7973
7974
void ImGui::SetWindowFocus(const char* name)
7975
0
{
7976
0
    if (name)
7977
0
    {
7978
0
        if (ImGuiWindow* window = FindWindowByName(name))
7979
0
            FocusWindow(window);
7980
0
    }
7981
0
    else
7982
0
    {
7983
0
        FocusWindow(NULL);
7984
0
    }
7985
0
}
7986
7987
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
7988
0
{
7989
0
    ImGuiContext& g = *GImGui;
7990
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7991
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
7992
0
    g.NextWindowData.PosVal = pos;
7993
0
    g.NextWindowData.PosPivotVal = pivot;
7994
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
7995
0
    g.NextWindowData.PosUndock = true;
7996
0
}
7997
7998
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
7999
270k
{
8000
270k
    ImGuiContext& g = *GImGui;
8001
270k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8002
270k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8003
270k
    g.NextWindowData.SizeVal = size;
8004
270k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8005
270k
}
8006
8007
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8008
0
{
8009
0
    ImGuiContext& g = *GImGui;
8010
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8011
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8012
0
    g.NextWindowData.SizeCallback = custom_callback;
8013
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8014
0
}
8015
8016
// Content size = inner scrollable rectangle, padded with WindowPadding.
8017
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8018
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8019
0
{
8020
0
    ImGuiContext& g = *GImGui;
8021
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8022
0
    g.NextWindowData.ContentSizeVal = ImFloor(size);
8023
0
}
8024
8025
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8026
0
{
8027
0
    ImGuiContext& g = *GImGui;
8028
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8029
0
    g.NextWindowData.ScrollVal = scroll;
8030
0
}
8031
8032
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8033
0
{
8034
0
    ImGuiContext& g = *GImGui;
8035
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8036
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8037
0
    g.NextWindowData.CollapsedVal = collapsed;
8038
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8039
0
}
8040
8041
void ImGui::SetNextWindowFocus()
8042
0
{
8043
0
    ImGuiContext& g = *GImGui;
8044
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8045
0
}
8046
8047
void ImGui::SetNextWindowBgAlpha(float alpha)
8048
0
{
8049
0
    ImGuiContext& g = *GImGui;
8050
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8051
0
    g.NextWindowData.BgAlphaVal = alpha;
8052
0
}
8053
8054
void ImGui::SetNextWindowViewport(ImGuiID id)
8055
0
{
8056
0
    ImGuiContext& g = *GImGui;
8057
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8058
0
    g.NextWindowData.ViewportId = id;
8059
0
}
8060
8061
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8062
0
{
8063
0
    ImGuiContext& g = *GImGui;
8064
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8065
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8066
0
    g.NextWindowData.DockId = id;
8067
0
}
8068
8069
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8070
0
{
8071
0
    ImGuiContext& g = *GImGui;
8072
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8073
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8074
0
    g.NextWindowData.WindowClass = *window_class;
8075
0
}
8076
8077
ImDrawList* ImGui::GetWindowDrawList()
8078
103k
{
8079
103k
    ImGuiWindow* window = GetCurrentWindow();
8080
103k
    return window->DrawList;
8081
103k
}
8082
8083
float ImGui::GetWindowDpiScale()
8084
0
{
8085
0
    ImGuiContext& g = *GImGui;
8086
0
    return g.CurrentDpiScale;
8087
0
}
8088
8089
ImGuiViewport* ImGui::GetWindowViewport()
8090
0
{
8091
0
    ImGuiContext& g = *GImGui;
8092
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8093
0
    return g.CurrentViewport;
8094
0
}
8095
8096
ImFont* ImGui::GetFont()
8097
143M
{
8098
143M
    return GImGui->Font;
8099
143M
}
8100
8101
float ImGui::GetFontSize()
8102
144M
{
8103
144M
    return GImGui->FontSize;
8104
144M
}
8105
8106
ImVec2 ImGui::GetFontTexUvWhitePixel()
8107
0
{
8108
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8109
0
}
8110
8111
void ImGui::SetWindowFontScale(float scale)
8112
0
{
8113
0
    IM_ASSERT(scale > 0.0f);
8114
0
    ImGuiContext& g = *GImGui;
8115
0
    ImGuiWindow* window = GetCurrentWindow();
8116
0
    window->FontWindowScale = scale;
8117
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8118
0
}
8119
8120
void ImGui::ActivateItem(ImGuiID id)
8121
0
{
8122
0
    ImGuiContext& g = *GImGui;
8123
0
    g.NavNextActivateId = id;
8124
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8125
0
}
8126
8127
void ImGui::PushFocusScope(ImGuiID id)
8128
440k
{
8129
440k
    ImGuiContext& g = *GImGui;
8130
440k
    g.FocusScopeStack.push_back(id);
8131
440k
    g.CurrentFocusScopeId = id;
8132
440k
}
8133
8134
void ImGui::PopFocusScope()
8135
440k
{
8136
440k
    ImGuiContext& g = *GImGui;
8137
440k
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
8138
440k
    g.FocusScopeStack.pop_back();
8139
440k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
8140
440k
}
8141
8142
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8143
void ImGui::SetKeyboardFocusHere(int offset)
8144
0
{
8145
0
    ImGuiContext& g = *GImGui;
8146
0
    ImGuiWindow* window = g.CurrentWindow;
8147
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8148
0
    IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8149
8150
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8151
    // When we refactor this function into ActivateItem() we may want to make this an option.
8152
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8153
    // is also automatically dropped in the event g.ActiveId is stolen.
8154
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8155
0
    {
8156
0
        IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8157
0
        return;
8158
0
    }
8159
8160
0
    SetNavWindow(window);
8161
8162
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8163
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8164
0
    if (offset == -1)
8165
0
    {
8166
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8167
0
    }
8168
0
    else
8169
0
    {
8170
0
        g.NavTabbingDir = 1;
8171
0
        g.NavTabbingCounter = offset + 1;
8172
0
    }
8173
0
}
8174
8175
void ImGui::SetItemDefaultFocus()
8176
0
{
8177
0
    ImGuiContext& g = *GImGui;
8178
0
    ImGuiWindow* window = g.CurrentWindow;
8179
0
    if (!window->Appearing)
8180
0
        return;
8181
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResultId == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8182
0
        return;
8183
8184
0
    g.NavInitRequest = false;
8185
0
    g.NavInitResultId = g.LastItemData.ID;
8186
0
    g.NavInitResultRectRel = WindowRectAbsToRel(window, g.LastItemData.Rect);
8187
0
    NavUpdateAnyRequestFlag();
8188
8189
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8190
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8191
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8192
0
}
8193
8194
void ImGui::SetStateStorage(ImGuiStorage* tree)
8195
0
{
8196
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8197
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8198
0
}
8199
8200
ImGuiStorage* ImGui::GetStateStorage()
8201
0
{
8202
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8203
0
    return window->DC.StateStorage;
8204
0
}
8205
8206
void ImGui::PushID(const char* str_id)
8207
103k
{
8208
103k
    ImGuiContext& g = *GImGui;
8209
103k
    ImGuiWindow* window = g.CurrentWindow;
8210
103k
    ImGuiID id = window->GetID(str_id);
8211
103k
    window->IDStack.push_back(id);
8212
103k
}
8213
8214
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8215
0
{
8216
0
    ImGuiContext& g = *GImGui;
8217
0
    ImGuiWindow* window = g.CurrentWindow;
8218
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8219
0
    window->IDStack.push_back(id);
8220
0
}
8221
8222
void ImGui::PushID(const void* ptr_id)
8223
0
{
8224
0
    ImGuiContext& g = *GImGui;
8225
0
    ImGuiWindow* window = g.CurrentWindow;
8226
0
    ImGuiID id = window->GetID(ptr_id);
8227
0
    window->IDStack.push_back(id);
8228
0
}
8229
8230
void ImGui::PushID(int int_id)
8231
0
{
8232
0
    ImGuiContext& g = *GImGui;
8233
0
    ImGuiWindow* window = g.CurrentWindow;
8234
0
    ImGuiID id = window->GetID(int_id);
8235
0
    window->IDStack.push_back(id);
8236
0
}
8237
8238
// Push a given id value ignoring the ID stack as a seed.
8239
void ImGui::PushOverrideID(ImGuiID id)
8240
0
{
8241
0
    ImGuiContext& g = *GImGui;
8242
0
    ImGuiWindow* window = g.CurrentWindow;
8243
0
    if (g.DebugHookIdInfo == id)
8244
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8245
0
    window->IDStack.push_back(id);
8246
0
}
8247
8248
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8249
// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
8250
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8251
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8252
0
{
8253
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8254
0
    ImGuiContext& g = *GImGui;
8255
0
    if (g.DebugHookIdInfo == id)
8256
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8257
0
    return id;
8258
0
}
8259
8260
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8261
0
{
8262
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8263
0
    ImGuiContext& g = *GImGui;
8264
0
    if (g.DebugHookIdInfo == id)
8265
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8266
0
    return id;
8267
0
}
8268
8269
void ImGui::PopID()
8270
103k
{
8271
103k
    ImGuiWindow* window = GImGui->CurrentWindow;
8272
103k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8273
103k
    window->IDStack.pop_back();
8274
103k
}
8275
8276
ImGuiID ImGui::GetID(const char* str_id)
8277
0
{
8278
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8279
0
    return window->GetID(str_id);
8280
0
}
8281
8282
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8283
0
{
8284
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8285
0
    return window->GetID(str_id_begin, str_id_end);
8286
0
}
8287
8288
ImGuiID ImGui::GetID(const void* ptr_id)
8289
0
{
8290
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8291
0
    return window->GetID(ptr_id);
8292
0
}
8293
8294
bool ImGui::IsRectVisible(const ImVec2& size)
8295
0
{
8296
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8297
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8298
0
}
8299
8300
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8301
0
{
8302
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8303
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8304
0
}
8305
8306
8307
//-----------------------------------------------------------------------------
8308
// [SECTION] INPUTS
8309
//-----------------------------------------------------------------------------
8310
// - GetKeyData() [Internal]
8311
// - GetKeyIndex() [Internal]
8312
// - GetKeyName()
8313
// - GetKeyChordName() [Internal]
8314
// - CalcTypematicRepeatAmount() [Internal]
8315
// - GetTypematicRepeatRate() [Internal]
8316
// - GetKeyPressedAmount() [Internal]
8317
// - GetKeyMagnitude2d() [Internal]
8318
//-----------------------------------------------------------------------------
8319
// - UpdateKeyRoutingTable() [Internal]
8320
// - GetRoutingIdFromOwnerId() [Internal]
8321
// - GetShortcutRoutingData() [Internal]
8322
// - CalcRoutingScore() [Internal]
8323
// - SetShortcutRouting() [Internal]
8324
// - TestShortcutRouting() [Internal]
8325
//-----------------------------------------------------------------------------
8326
// - IsKeyDown()
8327
// - IsKeyPressed()
8328
// - IsKeyReleased()
8329
//-----------------------------------------------------------------------------
8330
// - IsMouseDown()
8331
// - IsMouseClicked()
8332
// - IsMouseReleased()
8333
// - IsMouseDoubleClicked()
8334
// - GetMouseClickedCount()
8335
// - IsMouseHoveringRect() [Internal]
8336
// - IsMouseDragPastThreshold() [Internal]
8337
// - IsMouseDragging()
8338
// - GetMousePos()
8339
// - GetMousePosOnOpeningCurrentPopup()
8340
// - IsMousePosValid()
8341
// - IsAnyMouseDown()
8342
// - GetMouseDragDelta()
8343
// - ResetMouseDragDelta()
8344
// - GetMouseCursor()
8345
// - SetMouseCursor()
8346
//-----------------------------------------------------------------------------
8347
// - UpdateAliasKey()
8348
// - GetMergedModsFromKeys()
8349
// - UpdateKeyboardInputs()
8350
// - UpdateMouseInputs()
8351
//-----------------------------------------------------------------------------
8352
// - LockWheelingWindow [Internal]
8353
// - FindBestWheelingWindow [Internal]
8354
// - UpdateMouseWheel() [Internal]
8355
//-----------------------------------------------------------------------------
8356
// - SetNextFrameWantCaptureKeyboard()
8357
// - SetNextFrameWantCaptureMouse()
8358
//-----------------------------------------------------------------------------
8359
// - GetInputSourceName() [Internal]
8360
// - DebugPrintInputEvent() [Internal]
8361
// - UpdateInputEvents() [Internal]
8362
//-----------------------------------------------------------------------------
8363
// - GetKeyOwner() [Internal]
8364
// - TestKeyOwner() [Internal]
8365
// - SetKeyOwner() [Internal]
8366
// - SetItemKeyOwner() [Internal]
8367
// - Shortcut() [Internal]
8368
//-----------------------------------------------------------------------------
8369
8370
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8371
5.66M
{
8372
5.66M
    ImGuiContext& g = *ctx;
8373
8374
    // Special storage location for mods
8375
5.66M
    if (key & ImGuiMod_Mask_)
8376
1.50M
        key = ConvertSingleModFlagToKey(ctx, key);
8377
8378
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8379
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8380
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8381
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
8382
#else
8383
5.66M
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8384
5.66M
#endif
8385
5.66M
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8386
5.66M
}
8387
8388
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8389
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8390
{
8391
    ImGuiContext& g = *GImGui;
8392
    IM_ASSERT(IsNamedKey(key));
8393
    const ImGuiKeyData* key_data = GetKeyData(key);
8394
    return (ImGuiKey)(key_data - g.IO.KeysData);
8395
}
8396
#endif
8397
8398
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8399
static const char* const GKeyNames[] =
8400
{
8401
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8402
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8403
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8404
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8405
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8406
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8407
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8408
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8409
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8410
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8411
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8412
    "GamepadStart", "GamepadBack",
8413
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8414
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8415
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8416
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8417
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8418
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8419
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8420
};
8421
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8422
8423
const char* ImGui::GetKeyName(ImGuiKey key)
8424
0
{
8425
0
    ImGuiContext& g = *GImGui;
8426
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8427
0
    IM_ASSERT((IsNamedKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8428
#else
8429
    if (IsLegacyKey(key))
8430
    {
8431
        if (g.IO.KeyMap[key] == -1)
8432
            return "N/A";
8433
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8434
        key = (ImGuiKey)g.IO.KeyMap[key];
8435
    }
8436
#endif
8437
0
    if (key == ImGuiKey_None)
8438
0
        return "None";
8439
0
    if (key & ImGuiMod_Mask_)
8440
0
        key = ConvertSingleModFlagToKey(&g, key);
8441
0
    if (!IsNamedKey(key))
8442
0
        return "Unknown";
8443
8444
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8445
0
}
8446
8447
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8448
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8449
0
{
8450
0
    ImGuiContext& g = *GImGui;
8451
0
    if (key_chord & ImGuiMod_Shortcut)
8452
0
        key_chord = ConvertShortcutMod(key_chord);
8453
0
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8454
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8455
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8456
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8457
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8458
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8459
0
}
8460
8461
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8462
// t1 = current time (e.g.: g.Time)
8463
// An event is triggered at:
8464
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8465
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8466
38.8k
{
8467
38.8k
    if (t1 == 0.0f)
8468
0
        return 1;
8469
38.8k
    if (t0 >= t1)
8470
0
        return 0;
8471
38.8k
    if (repeat_rate <= 0.0f)
8472
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8473
38.8k
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8474
38.8k
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8475
38.8k
    const int count = count_t1 - count_t0;
8476
38.8k
    return count;
8477
38.8k
}
8478
8479
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8480
74.7k
{
8481
74.7k
    ImGuiContext& g = *GImGui;
8482
74.7k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8483
74.7k
    {
8484
12.6k
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8485
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8486
62.0k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8487
74.7k
    }
8488
74.7k
}
8489
8490
// Return value representing the number of presses in the last time period, for the given repeat rate
8491
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8492
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8493
38.8k
{
8494
38.8k
    ImGuiContext& g = *GImGui;
8495
38.8k
    const ImGuiKeyData* key_data = GetKeyData(key);
8496
38.8k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8497
0
        return 0;
8498
38.8k
    const float t = key_data->DownDuration;
8499
38.8k
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8500
38.8k
}
8501
8502
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8503
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8504
0
{
8505
0
    return ImVec2(
8506
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8507
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8508
0
}
8509
8510
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8511
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8512
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8513
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8514
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8515
167k
{
8516
167k
    ImGuiContext& g = *GImGui;
8517
167k
    rt->EntriesNext.resize(0);
8518
23.5M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8519
23.3M
    {
8520
23.3M
        const int new_routing_start_idx = rt->EntriesNext.Size;
8521
23.3M
        ImGuiKeyRoutingData* routing_entry;
8522
23.3M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8523
0
        {
8524
0
            routing_entry = &rt->Entries[old_routing_idx];
8525
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8526
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8527
0
            routing_entry->RoutingNextScore = 255;
8528
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8529
0
                continue;
8530
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8531
8532
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8533
0
            if (routing_entry->Mods == g.IO.KeyMods)
8534
0
            {
8535
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
8536
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8537
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8538
0
            }
8539
0
        }
8540
8541
        // Rewrite linked-list
8542
23.3M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8543
23.3M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8544
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8545
23.3M
    }
8546
167k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8547
167k
}
8548
8549
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8550
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8551
0
{
8552
0
    ImGuiContext& g = *GImGui;
8553
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8554
0
}
8555
8556
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8557
0
{
8558
    // Majority of shortcuts will be Key + any number of Mods
8559
    // We accept _Single_ mod with ImGuiKey_None.
8560
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8561
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8562
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8563
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8564
0
    ImGuiContext& g = *GImGui;
8565
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8566
0
    ImGuiKeyRoutingData* routing_data;
8567
0
    if (key_chord & ImGuiMod_Shortcut)
8568
0
        key_chord = ConvertShortcutMod(key_chord);
8569
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8570
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8571
0
    if (key == ImGuiKey_None)
8572
0
        key = ConvertSingleModFlagToKey(&g, mods);
8573
0
    IM_ASSERT(IsNamedKey(key));
8574
8575
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8576
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8577
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8578
0
    {
8579
0
        routing_data = &rt->Entries[idx];
8580
0
        if (routing_data->Mods == mods)
8581
0
            return routing_data;
8582
0
    }
8583
8584
    // Add to linked-list
8585
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8586
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
8587
0
    routing_data = &rt->Entries[routing_data_idx];
8588
0
    routing_data->Mods = (ImU16)mods;
8589
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8590
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8591
0
    return routing_data;
8592
0
}
8593
8594
// Current score encoding (lower is highest priority):
8595
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8596
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8597
//  -   2: ImGuiInputFlags_RouteGlobal
8598
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8599
//  - 254: ImGuiInputFlags_RouteGlobalLow
8600
//  - 255: never route
8601
// 'flags' should include an explicit routing policy
8602
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8603
0
{
8604
0
    if (flags & ImGuiInputFlags_RouteFocused)
8605
0
    {
8606
0
        ImGuiContext& g = *GImGui;
8607
0
        ImGuiWindow* focused = g.NavWindow;
8608
8609
        // ActiveID gets top priority
8610
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8611
0
        if (owner_id != 0 && g.ActiveId == owner_id)
8612
0
            return 1;
8613
8614
        // Score based on distance to focused window (lower is better)
8615
        // Assuming both windows are submitting a routing request,
8616
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8617
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8618
        // Assuming only WindowA is submitting a routing request,
8619
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8620
0
        if (focused != NULL && focused->RootWindow == location->RootWindow)
8621
0
            for (int next_score = 3; focused != NULL; next_score++)
8622
0
            {
8623
0
                if (focused == location)
8624
0
                {
8625
0
                    IM_ASSERT(next_score < 255);
8626
0
                    return next_score;
8627
0
                }
8628
0
                focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8629
0
            }
8630
0
        return 255;
8631
0
    }
8632
8633
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8634
0
    if (flags & ImGuiInputFlags_RouteGlobal)
8635
0
        return 2;
8636
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8637
0
        return 254;
8638
0
    return 0;
8639
0
}
8640
8641
// Request a desired route for an input chord (key + mods).
8642
// Return true if the route is available this frame.
8643
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8644
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8645
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8646
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8647
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8648
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8649
334k
{
8650
334k
    ImGuiContext& g = *GImGui;
8651
334k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8652
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8653
334k
    else
8654
334k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8655
8656
334k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8657
0
        if (g.NavWindow == NULL)
8658
0
            return false;
8659
334k
    if (flags & ImGuiInputFlags_RouteAlways)
8660
334k
        return true;
8661
8662
0
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8663
0
    if (score == 255)
8664
0
        return false;
8665
8666
    // Submit routing for NEXT frame (assuming score is sufficient)
8667
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8668
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8669
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8670
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8671
0
    if (score < routing_data->RoutingNextScore)
8672
0
    {
8673
0
        routing_data->RoutingNext = routing_id;
8674
0
        routing_data->RoutingNextScore = (ImU8)score;
8675
0
    }
8676
8677
    // Return routing state for CURRENT frame
8678
0
    return routing_data->RoutingCurr == routing_id;
8679
0
}
8680
8681
// Currently unused by core (but used by tests)
8682
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8683
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8684
0
{
8685
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8686
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8687
0
    return routing_data->RoutingCurr == routing_id;
8688
0
}
8689
8690
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8691
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8692
bool ImGui::IsKeyDown(ImGuiKey key)
8693
2.51M
{
8694
2.51M
    return IsKeyDown(key, ImGuiKeyOwner_Any);
8695
2.51M
}
8696
8697
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8698
2.66M
{
8699
2.66M
    const ImGuiKeyData* key_data = GetKeyData(key);
8700
2.66M
    if (!key_data->Down)
8701
2.60M
        return false;
8702
62.7k
    if (!TestKeyOwner(key, owner_id))
8703
3.14k
        return false;
8704
59.6k
    return true;
8705
62.7k
}
8706
8707
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8708
940k
{
8709
940k
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8710
940k
}
8711
8712
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
8713
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
8714
1.76M
{
8715
1.76M
    const ImGuiKeyData* key_data = GetKeyData(key);
8716
1.76M
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8717
1.67M
        return false;
8718
90.3k
    const float t = key_data->DownDuration;
8719
90.3k
    if (t < 0.0f)
8720
0
        return false;
8721
90.3k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8722
8723
90.3k
    bool pressed = (t == 0.0f);
8724
90.3k
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
8725
74.7k
    {
8726
74.7k
        float repeat_delay, repeat_rate;
8727
74.7k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
8728
74.7k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
8729
74.7k
    }
8730
90.3k
    if (!pressed)
8731
71.5k
        return false;
8732
18.7k
    if (!TestKeyOwner(key, owner_id))
8733
229
        return false;
8734
18.5k
    return true;
8735
18.7k
}
8736
8737
bool ImGui::IsKeyReleased(ImGuiKey key)
8738
0
{
8739
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
8740
0
}
8741
8742
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
8743
0
{
8744
0
    const ImGuiKeyData* key_data = GetKeyData(key);
8745
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
8746
0
        return false;
8747
0
    if (!TestKeyOwner(key, owner_id))
8748
0
        return false;
8749
0
    return true;
8750
0
}
8751
8752
bool ImGui::IsMouseDown(ImGuiMouseButton button)
8753
175
{
8754
175
    ImGuiContext& g = *GImGui;
8755
175
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8756
175
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
8757
175
}
8758
8759
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
8760
117
{
8761
117
    ImGuiContext& g = *GImGui;
8762
117
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8763
117
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
8764
117
}
8765
8766
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
8767
23.5k
{
8768
23.5k
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8769
23.5k
}
8770
8771
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
8772
24.2k
{
8773
24.2k
    ImGuiContext& g = *GImGui;
8774
24.2k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8775
24.2k
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8776
14.2k
        return false;
8777
9.96k
    const float t = g.IO.MouseDownDuration[button];
8778
9.96k
    if (t < 0.0f)
8779
0
        return false;
8780
9.96k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8781
8782
9.96k
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
8783
9.96k
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
8784
9.96k
    if (!pressed)
8785
8.61k
        return false;
8786
8787
1.35k
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
8788
0
        return false;
8789
8790
1.35k
    return true;
8791
1.35k
}
8792
8793
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
8794
0
{
8795
0
    ImGuiContext& g = *GImGui;
8796
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8797
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
8798
0
}
8799
8800
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
8801
745
{
8802
745
    ImGuiContext& g = *GImGui;
8803
745
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8804
745
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
8805
745
}
8806
8807
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
8808
23.5k
{
8809
23.5k
    ImGuiContext& g = *GImGui;
8810
23.5k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8811
23.5k
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
8812
23.5k
}
8813
8814
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
8815
0
{
8816
0
    ImGuiContext& g = *GImGui;
8817
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8818
0
    return g.IO.MouseClickedCount[button];
8819
0
}
8820
8821
// Test if mouse cursor is hovering given rectangle
8822
// NB- Rectangle is clipped by our current clip setting
8823
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
8824
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
8825
1.12M
{
8826
1.12M
    ImGuiContext& g = *GImGui;
8827
8828
    // Clip
8829
1.12M
    ImRect rect_clipped(r_min, r_max);
8830
1.12M
    if (clip)
8831
686k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
8832
8833
    // Expand for touch input
8834
1.12M
    const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
8835
1.12M
    if (!rect_for_touch.Contains(g.IO.MousePos))
8836
1.06M
        return false;
8837
59.2k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
8838
0
        return false;
8839
59.2k
    return true;
8840
59.2k
}
8841
8842
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
8843
// [Internal] This doesn't test if the button is pressed
8844
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
8845
8.63k
{
8846
8.63k
    ImGuiContext& g = *GImGui;
8847
8.63k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8848
8.63k
    if (lock_threshold < 0.0f)
8849
8.63k
        lock_threshold = g.IO.MouseDragThreshold;
8850
8.63k
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
8851
8.63k
}
8852
8853
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
8854
22.2k
{
8855
22.2k
    ImGuiContext& g = *GImGui;
8856
22.2k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8857
22.2k
    if (!g.IO.MouseDown[button])
8858
13.6k
        return false;
8859
8.63k
    return IsMouseDragPastThreshold(button, lock_threshold);
8860
22.2k
}
8861
8862
ImVec2 ImGui::GetMousePos()
8863
38.2k
{
8864
38.2k
    ImGuiContext& g = *GImGui;
8865
38.2k
    return g.IO.MousePos;
8866
38.2k
}
8867
8868
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
8869
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
8870
0
{
8871
0
    ImGuiContext& g = *GImGui;
8872
0
    if (g.BeginPopupStack.Size > 0)
8873
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
8874
0
    return g.IO.MousePos;
8875
0
}
8876
8877
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
8878
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
8879
593k
{
8880
    // The assert is only to silence a false-positive in XCode Static Analysis.
8881
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
8882
593k
    IM_ASSERT(GImGui != NULL);
8883
593k
    const float MOUSE_INVALID = -256000.0f;
8884
593k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
8885
593k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
8886
593k
}
8887
8888
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
8889
bool ImGui::IsAnyMouseDown()
8890
0
{
8891
0
    ImGuiContext& g = *GImGui;
8892
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
8893
0
        if (g.IO.MouseDown[n])
8894
0
            return true;
8895
0
    return false;
8896
0
}
8897
8898
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
8899
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
8900
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
8901
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
8902
0
{
8903
0
    ImGuiContext& g = *GImGui;
8904
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8905
0
    if (lock_threshold < 0.0f)
8906
0
        lock_threshold = g.IO.MouseDragThreshold;
8907
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
8908
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
8909
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
8910
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
8911
0
    return ImVec2(0.0f, 0.0f);
8912
0
}
8913
8914
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
8915
0
{
8916
0
    ImGuiContext& g = *GImGui;
8917
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8918
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
8919
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
8920
0
}
8921
8922
// Get desired mouse cursor shape.
8923
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
8924
// updated during the frame, and locked in EndFrame()/Render().
8925
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
8926
ImGuiMouseCursor ImGui::GetMouseCursor()
8927
0
{
8928
0
    ImGuiContext& g = *GImGui;
8929
0
    return g.MouseCursor;
8930
0
}
8931
8932
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
8933
14.2k
{
8934
14.2k
    ImGuiContext& g = *GImGui;
8935
14.2k
    g.MouseCursor = cursor_type;
8936
14.2k
}
8937
8938
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
8939
1.16M
{
8940
1.16M
    IM_ASSERT(ImGui::IsAliasKey(key));
8941
1.16M
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
8942
1.16M
    key_data->Down = v;
8943
1.16M
    key_data->AnalogValue = analog_value;
8944
1.16M
}
8945
8946
// [Internal] Do not use directly
8947
static ImGuiKeyChord GetMergedModsFromKeys()
8948
334k
{
8949
334k
    ImGuiKeyChord mods = 0;
8950
334k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
8951
334k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
8952
334k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
8953
334k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
8954
334k
    return mods;
8955
334k
}
8956
8957
static void ImGui::UpdateKeyboardInputs()
8958
167k
{
8959
167k
    ImGuiContext& g = *GImGui;
8960
167k
    ImGuiIO& io = g.IO;
8961
8962
    // Import legacy keys or verify they are not used
8963
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8964
    if (io.BackendUsingLegacyKeyArrays == 0)
8965
    {
8966
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
8967
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
8968
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
8969
    }
8970
    else
8971
    {
8972
        if (g.FrameCount == 0)
8973
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
8974
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
8975
8976
        // Build reverse KeyMap (Named -> Legacy)
8977
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
8978
            if (io.KeyMap[n] != -1)
8979
            {
8980
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
8981
                io.KeyMap[io.KeyMap[n]] = n;
8982
            }
8983
8984
        // Import legacy keys into new ones
8985
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
8986
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
8987
            {
8988
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
8989
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
8990
                io.KeysData[key].Down = io.KeysDown[n];
8991
                if (key != n)
8992
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
8993
                io.BackendUsingLegacyKeyArrays = 1;
8994
            }
8995
        if (io.BackendUsingLegacyKeyArrays == 1)
8996
        {
8997
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
8998
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
8999
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9000
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9001
        }
9002
    }
9003
9004
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9005
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9006
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9007
    {
9008
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9009
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9010
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9011
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9012
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9013
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9014
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9015
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9016
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9017
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9018
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9019
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9020
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9021
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9022
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9023
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9024
        #undef NAV_MAP_KEY
9025
    }
9026
#endif
9027
#endif
9028
9029
    // Update aliases
9030
1.00M
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9031
835k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9032
167k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9033
167k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9034
9035
    // Synchronize io.KeyMods and io.KeyXXX values.
9036
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9037
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9038
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9039
167k
    io.KeyMods = GetMergedModsFromKeys();
9040
167k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9041
167k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9042
167k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9043
167k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9044
9045
    // Clear gamepad data if disabled
9046
167k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9047
4.17M
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9048
4.01M
        {
9049
4.01M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9050
4.01M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9051
4.01M
        }
9052
9053
    // Update keys
9054
23.5M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9055
23.3M
    {
9056
23.3M
        ImGuiKeyData* key_data = &io.KeysData[i];
9057
23.3M
        key_data->DownDurationPrev = key_data->DownDuration;
9058
23.3M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9059
23.3M
    }
9060
9061
    // Update keys/input owner (named keys only): one entry per key
9062
23.5M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9063
23.3M
    {
9064
23.3M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9065
23.3M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9066
23.3M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9067
23.3M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9068
23.1M
            owner_data->OwnerNext = ImGuiKeyOwner_None;
9069
23.3M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9070
23.3M
    }
9071
9072
167k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9073
167k
}
9074
9075
static void ImGui::UpdateMouseInputs()
9076
167k
{
9077
167k
    ImGuiContext& g = *GImGui;
9078
167k
    ImGuiIO& io = g.IO;
9079
9080
    // Mouse Wheel swapping flag
9081
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9082
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9083
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9084
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9085
167k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9086
9087
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9088
167k
    if (IsMousePosValid(&io.MousePos))
9089
67.8k
        io.MousePos = g.MouseLastValidPos = ImFloorSigned(io.MousePos);
9090
9091
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9092
167k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9093
64.0k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9094
103k
    else
9095
103k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9096
9097
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9098
167k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9099
3.89k
        g.NavDisableMouseHover = false;
9100
9101
167k
    io.MousePosPrev = io.MousePos;
9102
1.00M
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9103
835k
    {
9104
835k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9105
835k
        io.MouseClickedCount[i] = 0; // Will be filled below
9106
835k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9107
835k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9108
835k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9109
835k
        if (io.MouseClicked[i])
9110
10.8k
        {
9111
10.8k
            bool is_repeated_click = false;
9112
10.8k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9113
6.12k
            {
9114
6.12k
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9115
6.12k
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9116
4.41k
                    is_repeated_click = true;
9117
6.12k
            }
9118
10.8k
            if (is_repeated_click)
9119
4.41k
                io.MouseClickedLastCount[i]++;
9120
6.47k
            else
9121
6.47k
                io.MouseClickedLastCount[i] = 1;
9122
10.8k
            io.MouseClickedTime[i] = g.Time;
9123
10.8k
            io.MouseClickedPos[i] = io.MousePos;
9124
10.8k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9125
10.8k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9126
10.8k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9127
10.8k
        }
9128
824k
        else if (io.MouseDown[i])
9129
79.4k
        {
9130
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9131
79.4k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9132
79.4k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9133
79.4k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9134
79.4k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9135
79.4k
        }
9136
9137
        // We provide io.MouseDoubleClicked[] as a legacy service
9138
835k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9139
9140
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9141
835k
        if (io.MouseClicked[i])
9142
10.8k
            g.NavDisableMouseHover = false;
9143
835k
    }
9144
167k
}
9145
9146
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9147
59
{
9148
59
    ImGuiContext& g = *GImGui;
9149
59
    if (window)
9150
35
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9151
24
    else
9152
24
        g.WheelingWindowReleaseTimer = 0.0f;
9153
59
    if (g.WheelingWindow == window)
9154
11
        return;
9155
48
    IMGUI_DEBUG_LOG_IO("LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9156
48
    g.WheelingWindow = window;
9157
48
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9158
48
    if (window == NULL)
9159
24
    {
9160
24
        g.WheelingWindowStartFrame = -1;
9161
24
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9162
24
    }
9163
48
}
9164
9165
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9166
164
{
9167
    // For each axis, find window in the hierarchy that may want to use scrolling
9168
164
    ImGuiContext& g = *GImGui;
9169
164
    ImGuiWindow* windows[2] = { NULL, NULL };
9170
492
    for (int axis = 0; axis < 2; axis++)
9171
328
        if (wheel[axis] != 0.0f)
9172
452
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9173
214
            {
9174
                // Bubble up into parent window if:
9175
                // - a child window doesn't allow any scrolling.
9176
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9177
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9178
214
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9179
214
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9180
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9181
214
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9182
3
                    break; // select this window
9183
214
            }
9184
164
    if (windows[0] == NULL && windows[1] == NULL)
9185
0
        return NULL;
9186
9187
    // If there's only one window or only one axis then there's no ambiguity
9188
164
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9189
163
        return windows[1] ? windows[1] : windows[0];
9190
9191
    // If candidate are different windows we need to decide which one to prioritize
9192
    // - First frame: only find a winner if one axis is zero.
9193
    // - Subsequent frames: only find a winner when one is more than the other.
9194
1
    if (g.WheelingWindowStartFrame == -1)
9195
1
        g.WheelingWindowStartFrame = g.FrameCount;
9196
1
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9197
1
    {
9198
1
        g.WheelingWindowWheelRemainder = wheel;
9199
1
        return NULL;
9200
1
    }
9201
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9202
1
}
9203
9204
// Called by NewFrame()
9205
void ImGui::UpdateMouseWheel()
9206
167k
{
9207
    // Reset the locked window if we move the mouse or after the timer elapses.
9208
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9209
167k
    ImGuiContext& g = *GImGui;
9210
167k
    if (g.WheelingWindow != NULL)
9211
341
    {
9212
341
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9213
341
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9214
9
            g.WheelingWindowReleaseTimer = 0.0f;
9215
341
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9216
24
            LockWheelingWindow(NULL, 0.0f);
9217
341
    }
9218
9219
167k
    ImVec2 wheel;
9220
167k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9221
167k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9222
9223
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9224
167k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9225
167k
    if (!mouse_window || mouse_window->Collapsed)
9226
141k
        return;
9227
9228
    // Zoom / Scale window
9229
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9230
25.6k
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9231
0
    {
9232
0
        LockWheelingWindow(mouse_window, wheel.y);
9233
0
        ImGuiWindow* window = mouse_window;
9234
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9235
0
        const float scale = new_font_scale / window->FontWindowScale;
9236
0
        window->FontWindowScale = new_font_scale;
9237
0
        if (window == window->RootWindow)
9238
0
        {
9239
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9240
0
            SetWindowPos(window, window->Pos + offset, 0);
9241
0
            window->Size = ImFloor(window->Size * scale);
9242
0
            window->SizeFull = ImFloor(window->SizeFull * scale);
9243
0
        }
9244
0
        return;
9245
0
    }
9246
25.6k
    if (g.IO.KeyCtrl)
9247
0
        return;
9248
9249
    // Mouse wheel scrolling
9250
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9251
25.6k
    if (g.IO.MouseWheelRequestAxisSwap)
9252
0
        wheel = ImVec2(wheel.y, 0.0f);
9253
9254
    // Maintain a rough average of moving magnitude on both axises
9255
    // FIXME: should by based on wall clock time rather than frame-counter
9256
25.6k
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9257
25.6k
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9258
9259
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9260
25.6k
    wheel += g.WheelingWindowWheelRemainder;
9261
25.6k
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9262
25.6k
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9263
25.4k
        return;
9264
9265
    // Mouse wheel scrolling: find target and apply
9266
    // - don't renew lock if axis doesn't apply on the window.
9267
    // - select a main axis when both axises are being moved.
9268
191
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9269
190
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9270
190
        {
9271
190
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9272
190
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9273
8
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9274
190
            if (do_scroll[ImGuiAxis_X])
9275
14
            {
9276
14
                LockWheelingWindow(window, wheel.x);
9277
14
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9278
14
                float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
9279
14
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9280
14
            }
9281
190
            if (do_scroll[ImGuiAxis_Y])
9282
21
            {
9283
21
                LockWheelingWindow(window, wheel.y);
9284
21
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9285
21
                float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
9286
21
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9287
21
            }
9288
190
        }
9289
191
}
9290
9291
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9292
0
{
9293
0
    ImGuiContext& g = *GImGui;
9294
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9295
0
}
9296
9297
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9298
0
{
9299
0
    ImGuiContext& g = *GImGui;
9300
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9301
0
}
9302
9303
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9304
static const char* GetInputSourceName(ImGuiInputSource source)
9305
0
{
9306
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Clipboard" };
9307
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9308
0
    return input_source_names[source];
9309
0
}
9310
static const char* GetMouseSourceName(ImGuiMouseSource source)
9311
0
{
9312
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9313
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9314
0
    return mouse_source_names[source];
9315
0
}
9316
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9317
0
{
9318
0
    ImGuiContext& g = *GImGui;
9319
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("%s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("%s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9320
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("%s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9321
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("%s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9322
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("%s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9323
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("%s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9324
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("%s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9325
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("%s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9326
0
}
9327
#endif
9328
9329
// Process input queue
9330
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9331
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9332
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9333
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9334
167k
{
9335
167k
    ImGuiContext& g = *GImGui;
9336
167k
    ImGuiIO& io = g.IO;
9337
9338
    // Only trickle chars<>key when working with InputText()
9339
    // FIXME: InputText() could parse event trail?
9340
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9341
167k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9342
9343
167k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9344
167k
    int  mouse_button_changed = 0x00;
9345
167k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9346
9347
167k
    int event_n = 0;
9348
220k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9349
67.6k
    {
9350
67.6k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9351
67.6k
        if (e->Type == ImGuiInputEventType_MousePos)
9352
12.9k
        {
9353
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9354
12.9k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9355
12.9k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9356
3.21k
                break;
9357
9.70k
            io.MousePos = event_pos;
9358
9.70k
            io.MouseSource = e->MousePos.MouseSource;
9359
9.70k
            mouse_moved = true;
9360
9.70k
        }
9361
54.7k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9362
20.3k
        {
9363
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9364
20.3k
            const ImGuiMouseButton button = e->MouseButton.Button;
9365
20.3k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9366
20.3k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9367
5.29k
                break;
9368
15.0k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9369
0
                break;
9370
15.0k
            io.MouseDown[button] = e->MouseButton.Down;
9371
15.0k
            io.MouseSource = e->MouseButton.MouseSource;
9372
15.0k
            mouse_button_changed |= (1 << button);
9373
15.0k
        }
9374
34.4k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9375
7.40k
        {
9376
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9377
7.40k
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9378
2.94k
                break;
9379
4.45k
            io.MouseWheelH += e->MouseWheel.WheelX;
9380
4.45k
            io.MouseWheel += e->MouseWheel.WheelY;
9381
4.45k
            io.MouseSource = e->MouseWheel.MouseSource;
9382
4.45k
            mouse_wheeled = true;
9383
4.45k
        }
9384
27.0k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9385
0
        {
9386
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9387
0
        }
9388
27.0k
        else if (e->Type == ImGuiInputEventType_Key)
9389
10.1k
        {
9390
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9391
10.1k
            ImGuiKey key = e->Key.Key;
9392
10.1k
            IM_ASSERT(key != ImGuiKey_None);
9393
10.1k
            ImGuiKeyData* key_data = GetKeyData(key);
9394
10.1k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9395
10.1k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9396
1.82k
                break;
9397
8.32k
            key_data->Down = e->Key.Down;
9398
8.32k
            key_data->AnalogValue = e->Key.AnalogValue;
9399
8.32k
            key_changed = true;
9400
8.32k
            key_changed_mask.SetBit(key_data_index);
9401
9402
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9403
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9404
            io.KeysDown[key_data_index] = key_data->Down;
9405
            if (io.KeyMap[key_data_index] != -1)
9406
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9407
#endif
9408
8.32k
        }
9409
16.8k
        else if (e->Type == ImGuiInputEventType_Text)
9410
14.2k
        {
9411
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9412
14.2k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9413
1.27k
                break;
9414
12.9k
            unsigned int c = e->Text.Char;
9415
12.9k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9416
12.9k
            if (trickle_interleaved_keys_and_text)
9417
0
                text_inputted = true;
9418
12.9k
        }
9419
2.61k
        else if (e->Type == ImGuiInputEventType_Focus)
9420
2.61k
        {
9421
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9422
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9423
2.61k
            const bool focus_lost = !e->AppFocused.Focused;
9424
2.61k
            io.AppFocusLost = focus_lost;
9425
2.61k
        }
9426
0
        else
9427
0
        {
9428
0
            IM_ASSERT(0 && "Unknown event!");
9429
0
        }
9430
67.6k
    }
9431
9432
    // Record trail (for domain-specific applications wanting to access a precise trail)
9433
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9434
220k
    for (int n = 0; n < event_n; n++)
9435
53.0k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9436
9437
    // [DEBUG]
9438
167k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9439
167k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9440
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9441
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9442
167k
#endif
9443
9444
    // Remaining events will be processed on the next frame
9445
167k
    if (event_n == g.InputEventsQueue.Size)
9446
152k
        g.InputEventsQueue.resize(0);
9447
14.5k
    else
9448
14.5k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9449
9450
    // Clear buttons state when focus is lost
9451
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9452
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9453
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9454
167k
    if (g.IO.AppFocusLost)
9455
2.20k
        g.IO.ClearInputKeys();
9456
167k
}
9457
9458
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9459
0
{
9460
0
    if (!IsNamedKeyOrModKey(key))
9461
0
        return ImGuiKeyOwner_None;
9462
9463
0
    ImGuiContext& g = *GImGui;
9464
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9465
0
    ImGuiID owner_id = owner_data->OwnerCurr;
9466
9467
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9468
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9469
0
            return ImGuiKeyOwner_None;
9470
9471
0
    return owner_id;
9472
0
}
9473
9474
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9475
// TestKeyOwner(..., None) : (owner == None)
9476
// TestKeyOwner(..., Any)  : no owner test
9477
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9478
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9479
417k
{
9480
417k
    if (!IsNamedKeyOrModKey(key))
9481
0
        return true;
9482
9483
417k
    ImGuiContext& g = *GImGui;
9484
417k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9485
24.1k
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9486
3.36k
            return false;
9487
9488
414k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9489
414k
    if (owner_id == ImGuiKeyOwner_Any)
9490
59.2k
        return (owner_data->LockThisFrame == false);
9491
9492
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9493
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9494
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9495
354k
    if (owner_data->OwnerCurr != owner_id)
9496
32
    {
9497
32
        if (owner_data->LockThisFrame)
9498
0
            return false;
9499
32
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9500
0
            return false;
9501
32
    }
9502
9503
354k
    return true;
9504
354k
}
9505
9506
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9507
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9508
// - SetKeyOwner(..., None)              : clears owner
9509
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9510
// - SetKeyOwner(..., Any or None, Lock) : set lock
9511
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9512
33
{
9513
33
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9514
33
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9515
9516
33
    ImGuiContext& g = *GImGui;
9517
33
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9518
33
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9519
9520
    // We cannot lock by default as it would likely break lots of legacy code.
9521
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9522
33
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9523
33
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9524
33
}
9525
9526
// Rarely used helper
9527
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9528
0
{
9529
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
9530
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
9531
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
9532
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
9533
0
    if (key_chord & ImGuiMod_Shortcut)  { SetKeyOwner(ImGuiMod_Shortcut, owner_id, flags); }
9534
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
9535
0
}
9536
9537
// This is more or less equivalent to:
9538
//   if (IsItemHovered() || IsItemActive())
9539
//       SetKeyOwner(key, GetItemID());
9540
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9541
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9542
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9543
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9544
0
{
9545
0
    ImGuiContext& g = *GImGui;
9546
0
    ImGuiID id = g.LastItemData.ID;
9547
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9548
0
        return;
9549
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9550
0
        flags |= ImGuiInputFlags_CondDefault_;
9551
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9552
0
    {
9553
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9554
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9555
0
    }
9556
0
}
9557
9558
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9559
334k
{
9560
334k
    ImGuiContext& g = *GImGui;
9561
9562
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9563
334k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9564
334k
        flags |= ImGuiInputFlags_RouteFocused;
9565
334k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9566
0
        return false;
9567
9568
334k
    if (key_chord & ImGuiMod_Shortcut)
9569
0
        key_chord = ConvertShortcutMod(key_chord);
9570
334k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9571
334k
    if (g.IO.KeyMods != mods)
9572
334k
        return false;
9573
9574
    // Special storage location for mods
9575
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9576
0
    if (key == ImGuiKey_None)
9577
0
        key = ConvertSingleModFlagToKey(&g, mods);
9578
9579
0
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateMask_))))
9580
0
        return false;
9581
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9582
9583
0
    return true;
9584
0
}
9585
9586
9587
//-----------------------------------------------------------------------------
9588
// [SECTION] ERROR CHECKING
9589
//-----------------------------------------------------------------------------
9590
9591
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9592
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9593
// If this triggers you have an issue:
9594
// - Most commonly: mismatched headers and compiled code version.
9595
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9596
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9597
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9598
//   Otherwise it is possible that different compilation units would see different structure layout
9599
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9600
3
{
9601
3
    bool error = false;
9602
3
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9603
3
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9604
3
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9605
3
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9606
3
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9607
3
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9608
3
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9609
3
    return !error;
9610
3
}
9611
9612
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9613
// This is causing issues and ambiguity and we need to retire that.
9614
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9615
// [Scenario 1]
9616
//  Previously this would make the window content size ~200x200:
9617
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9618
//  Instead, please submit an item:
9619
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9620
//  Alternative:
9621
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9622
// [Scenario 2]
9623
//  For reference this is one of the issue what we aim to fix with this change:
9624
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9625
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9626
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9627
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9628
0
{
9629
0
    ImGuiContext& g = *GImGui;
9630
0
    ImGuiWindow* window = g.CurrentWindow;
9631
0
    IM_ASSERT(window->DC.IsSetPos);
9632
0
    window->DC.IsSetPos = false;
9633
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9634
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9635
0
        return;
9636
0
    if (window->SkipItems)
9637
0
        return;
9638
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9639
#else
9640
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9641
#endif
9642
0
}
9643
9644
static void ImGui::ErrorCheckNewFrameSanityChecks()
9645
167k
{
9646
167k
    ImGuiContext& g = *GImGui;
9647
9648
    // Check user IM_ASSERT macro
9649
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9650
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9651
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9652
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9653
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9654
167k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9655
9656
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
9657
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
9658
#ifdef __EMSCRIPTEN__
9659
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
9660
        g.IO.DeltaTime = 0.00001f;
9661
#endif
9662
9663
    // Check user data
9664
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
9665
167k
    IM_ASSERT(g.Initialized);
9666
167k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
9667
167k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9668
167k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
9669
167k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
9670
167k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
9671
167k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
9672
167k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
9673
167k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
9674
167k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
9675
167k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
9676
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9677
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
9678
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
9679
9680
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
9681
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
9682
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
9683
#endif
9684
9685
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
9686
167k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
9687
3
        g.IO.ConfigWindowsResizeFromEdges = false;
9688
9689
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
9690
167k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
9691
167k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9692
167k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
9693
167k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9694
9695
    // Perform simple checks: multi-viewport and platform windows support
9696
167k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
9697
3
    {
9698
3
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
9699
0
        {
9700
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
9701
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
9702
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
9703
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
9704
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
9705
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
9706
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
9707
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
9708
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
9709
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
9710
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
9711
0
        }
9712
3
        else
9713
3
        {
9714
            // Disable feature, our backends do not support it
9715
3
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
9716
3
        }
9717
9718
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
9719
3
        for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
9720
0
        {
9721
0
            ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
9722
0
            IM_UNUSED(mon);
9723
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
9724
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
9725
0
            IM_ASSERT(mon.DpiScale != 0.0f);
9726
0
        }
9727
3
    }
9728
167k
}
9729
9730
static void ImGui::ErrorCheckEndFrameSanityChecks()
9731
167k
{
9732
167k
    ImGuiContext& g = *GImGui;
9733
9734
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
9735
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
9736
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
9737
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
9738
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
9739
    // while still correctly asserting on mid-frame key press events.
9740
167k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
9741
167k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
9742
167k
    IM_UNUSED(key_mods);
9743
9744
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
9745
    //ErrorCheckEndFrameRecover();
9746
9747
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
9748
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
9749
167k
    if (g.CurrentWindowStack.Size != 1)
9750
0
    {
9751
0
        if (g.CurrentWindowStack.Size > 1)
9752
0
        {
9753
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
9754
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
9755
0
            IM_UNUSED(window);
9756
0
            while (g.CurrentWindowStack.Size > 1)
9757
0
                End();
9758
0
        }
9759
0
        else
9760
0
        {
9761
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
9762
0
        }
9763
0
    }
9764
9765
167k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
9766
167k
}
9767
9768
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
9769
// Must be called during or before EndFrame().
9770
// This is generally flawed as we are not necessarily End/Popping things in the right order.
9771
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
9772
// FIXME: Can't recover from interleaved BeginTabBar/Begin
9773
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9774
0
{
9775
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
9776
0
    ImGuiContext& g = *GImGui;
9777
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
9778
0
    {
9779
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
9780
0
        ImGuiWindow* window = g.CurrentWindow;
9781
0
        if (g.CurrentWindowStack.Size == 1)
9782
0
        {
9783
0
            IM_ASSERT(window->IsFallbackWindow);
9784
0
            break;
9785
0
        }
9786
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
9787
0
        {
9788
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
9789
0
            EndChild();
9790
0
        }
9791
0
        else
9792
0
        {
9793
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
9794
0
            End();
9795
0
        }
9796
0
    }
9797
0
}
9798
9799
// Must be called before End()/EndChild()
9800
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9801
0
{
9802
0
    ImGuiContext& g = *GImGui;
9803
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
9804
0
    {
9805
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
9806
0
        EndTable();
9807
0
    }
9808
9809
0
    ImGuiWindow* window = g.CurrentWindow;
9810
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
9811
0
    IM_ASSERT(window != NULL);
9812
0
    while (g.CurrentTabBar != NULL) //-V1044
9813
0
    {
9814
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
9815
0
        EndTabBar();
9816
0
    }
9817
0
    while (window->DC.TreeDepth > 0)
9818
0
    {
9819
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
9820
0
        TreePop();
9821
0
    }
9822
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
9823
0
    {
9824
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
9825
0
        EndGroup();
9826
0
    }
9827
0
    while (window->IDStack.Size > 1)
9828
0
    {
9829
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
9830
0
        PopID();
9831
0
    }
9832
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
9833
0
    {
9834
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
9835
0
        EndDisabled();
9836
0
    }
9837
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
9838
0
    {
9839
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
9840
0
        PopStyleColor();
9841
0
    }
9842
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
9843
0
    {
9844
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
9845
0
        PopItemFlag();
9846
0
    }
9847
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
9848
0
    {
9849
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
9850
0
        PopStyleVar();
9851
0
    }
9852
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
9853
0
    {
9854
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
9855
0
        PopFocusScope();
9856
0
    }
9857
0
}
9858
9859
// Save current stack sizes for later compare
9860
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
9861
440k
{
9862
440k
    ImGuiContext& g = *ctx;
9863
440k
    ImGuiWindow* window = g.CurrentWindow;
9864
440k
    SizeOfIDStack = (short)window->IDStack.Size;
9865
440k
    SizeOfColorStack = (short)g.ColorStack.Size;
9866
440k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
9867
440k
    SizeOfFontStack = (short)g.FontStack.Size;
9868
440k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
9869
440k
    SizeOfGroupStack = (short)g.GroupStack.Size;
9870
440k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
9871
440k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
9872
440k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
9873
440k
}
9874
9875
// Compare to detect usage errors
9876
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
9877
440k
{
9878
440k
    ImGuiContext& g = *ctx;
9879
440k
    ImGuiWindow* window = g.CurrentWindow;
9880
440k
    IM_UNUSED(window);
9881
9882
    // Window stacks
9883
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
9884
440k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
9885
9886
    // Global stacks
9887
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
9888
440k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
9889
440k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
9890
440k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
9891
440k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
9892
440k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
9893
440k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
9894
440k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
9895
440k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
9896
440k
}
9897
9898
9899
//-----------------------------------------------------------------------------
9900
// [SECTION] LAYOUT
9901
//-----------------------------------------------------------------------------
9902
// - ItemSize()
9903
// - ItemAdd()
9904
// - SameLine()
9905
// - GetCursorScreenPos()
9906
// - SetCursorScreenPos()
9907
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
9908
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
9909
// - GetCursorStartPos()
9910
// - Indent()
9911
// - Unindent()
9912
// - SetNextItemWidth()
9913
// - PushItemWidth()
9914
// - PushMultiItemsWidths()
9915
// - PopItemWidth()
9916
// - CalcItemWidth()
9917
// - CalcItemSize()
9918
// - GetTextLineHeight()
9919
// - GetTextLineHeightWithSpacing()
9920
// - GetFrameHeight()
9921
// - GetFrameHeightWithSpacing()
9922
// - GetContentRegionMax()
9923
// - GetContentRegionMaxAbs() [Internal]
9924
// - GetContentRegionAvail(),
9925
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
9926
// - BeginGroup()
9927
// - EndGroup()
9928
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
9929
//-----------------------------------------------------------------------------
9930
9931
// Advance cursor given item size for layout.
9932
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
9933
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
9934
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
9935
205k
{
9936
205k
    ImGuiContext& g = *GImGui;
9937
205k
    ImGuiWindow* window = g.CurrentWindow;
9938
205k
    if (window->SkipItems)
9939
0
        return;
9940
9941
    // We increase the height in this function to accommodate for baseline offset.
9942
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
9943
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
9944
205k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
9945
9946
205k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
9947
205k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
9948
9949
    // Always align ourselves on pixel boundaries
9950
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
9951
205k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
9952
205k
    window->DC.CursorPosPrevLine.y = line_y1;
9953
205k
    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
9954
205k
    window->DC.CursorPos.y = IM_FLOOR(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
9955
205k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
9956
205k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
9957
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
9958
9959
205k
    window->DC.PrevLineSize.y = line_height;
9960
205k
    window->DC.CurrLineSize.y = 0.0f;
9961
205k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
9962
205k
    window->DC.CurrLineTextBaseOffset = 0.0f;
9963
205k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
9964
9965
    // Horizontal layout mode
9966
205k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
9967
0
        SameLine();
9968
205k
}
9969
9970
// Declare item bounding box for clipping and interaction.
9971
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
9972
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
9973
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
9974
759k
{
9975
759k
    ImGuiContext& g = *GImGui;
9976
759k
    ImGuiWindow* window = g.CurrentWindow;
9977
9978
    // Set item data
9979
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
9980
759k
    g.LastItemData.ID = id;
9981
759k
    g.LastItemData.Rect = bb;
9982
759k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
9983
759k
    g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags;
9984
759k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
9985
9986
    // Directional navigation processing
9987
759k
    if (id != 0)
9988
567k
    {
9989
567k
        KeepAliveID(id);
9990
9991
        // Runs prior to clipping early-out
9992
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
9993
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
9994
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
9995
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
9996
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
9997
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
9998
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
9999
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10000
567k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10001
347k
        {
10002
347k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10003
347k
            if (g.NavId == id || g.NavAnyRequest)
10004
17.9k
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10005
1.84k
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
10006
1.84k
                        NavProcessItem();
10007
347k
        }
10008
10009
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10010
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10011
        // READ THE FAQ: https://dearimgui.com/faq
10012
567k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10013
567k
    }
10014
759k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10015
10016
#ifdef IMGUI_ENABLE_TEST_ENGINE
10017
    if (id != 0)
10018
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10019
#endif
10020
10021
    // Clipping test
10022
    // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
10023
    //const bool is_clipped = IsClippedEx(bb, id);
10024
    //if (is_clipped)
10025
    //    return false;
10026
759k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10027
759k
    if (!is_rect_visible)
10028
115k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId))
10029
115k
            if (!g.LogEnabled)
10030
115k
                return false;
10031
10032
    // [DEBUG]
10033
643k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10034
643k
    if (id != 0 && id == g.DebugLocateId)
10035
0
        DebugLocateItemResolveWithLastItem();
10036
643k
#endif
10037
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10038
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10039
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10040
10041
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10042
643k
    if (is_rect_visible)
10043
643k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10044
643k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10045
41.4k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10046
643k
    return true;
10047
759k
}
10048
10049
// Gets back to previous line and continue with horizontal layout
10050
//      offset_from_start_x == 0 : follow right after previous item
10051
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10052
//      spacing_w < 0            : use default spacing if pos_x == 0, no spacing if pos_x != 0
10053
//      spacing_w >= 0           : enforce spacing amount
10054
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10055
0
{
10056
0
    ImGuiContext& g = *GImGui;
10057
0
    ImGuiWindow* window = g.CurrentWindow;
10058
0
    if (window->SkipItems)
10059
0
        return;
10060
10061
0
    if (offset_from_start_x != 0.0f)
10062
0
    {
10063
0
        if (spacing_w < 0.0f)
10064
0
            spacing_w = 0.0f;
10065
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10066
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10067
0
    }
10068
0
    else
10069
0
    {
10070
0
        if (spacing_w < 0.0f)
10071
0
            spacing_w = g.Style.ItemSpacing.x;
10072
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10073
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10074
0
    }
10075
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
10076
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10077
0
    window->DC.IsSameLine = true;
10078
0
}
10079
10080
ImVec2 ImGui::GetCursorScreenPos()
10081
141k
{
10082
141k
    ImGuiWindow* window = GetCurrentWindowRead();
10083
141k
    return window->DC.CursorPos;
10084
141k
}
10085
10086
// 2022/08/05: Setting cursor position also extend boundaries (via modifying CursorMaxPos) used to compute window size, group size etc.
10087
// I believe this was is a judicious choice but it's probably being relied upon (it has been the case since 1.31 and 1.50)
10088
// It would be sane if we requested user to use SetCursorPos() + Dummy(ImVec2(0,0)) to extend CursorMaxPos...
10089
void ImGui::SetCursorScreenPos(const ImVec2& pos)
10090
0
{
10091
0
    ImGuiWindow* window = GetCurrentWindow();
10092
0
    window->DC.CursorPos = pos;
10093
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10094
0
    window->DC.IsSetPos = true;
10095
0
}
10096
10097
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10098
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
10099
ImVec2 ImGui::GetCursorPos()
10100
0
{
10101
0
    ImGuiWindow* window = GetCurrentWindowRead();
10102
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
10103
0
}
10104
10105
float ImGui::GetCursorPosX()
10106
0
{
10107
0
    ImGuiWindow* window = GetCurrentWindowRead();
10108
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10109
0
}
10110
10111
float ImGui::GetCursorPosY()
10112
0
{
10113
0
    ImGuiWindow* window = GetCurrentWindowRead();
10114
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10115
0
}
10116
10117
void ImGui::SetCursorPos(const ImVec2& local_pos)
10118
0
{
10119
0
    ImGuiWindow* window = GetCurrentWindow();
10120
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10121
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10122
0
    window->DC.IsSetPos = true;
10123
0
}
10124
10125
void ImGui::SetCursorPosX(float x)
10126
0
{
10127
0
    ImGuiWindow* window = GetCurrentWindow();
10128
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10129
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10130
0
    window->DC.IsSetPos = true;
10131
0
}
10132
10133
void ImGui::SetCursorPosY(float y)
10134
0
{
10135
0
    ImGuiWindow* window = GetCurrentWindow();
10136
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10137
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10138
0
    window->DC.IsSetPos = true;
10139
0
}
10140
10141
ImVec2 ImGui::GetCursorStartPos()
10142
0
{
10143
0
    ImGuiWindow* window = GetCurrentWindowRead();
10144
0
    return window->DC.CursorStartPos - window->Pos;
10145
0
}
10146
10147
void ImGui::Indent(float indent_w)
10148
0
{
10149
0
    ImGuiContext& g = *GImGui;
10150
0
    ImGuiWindow* window = GetCurrentWindow();
10151
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10152
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10153
0
}
10154
10155
void ImGui::Unindent(float indent_w)
10156
0
{
10157
0
    ImGuiContext& g = *GImGui;
10158
0
    ImGuiWindow* window = GetCurrentWindow();
10159
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10160
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10161
0
}
10162
10163
// Affect large frame+labels widgets only.
10164
void ImGui::SetNextItemWidth(float item_width)
10165
0
{
10166
0
    ImGuiContext& g = *GImGui;
10167
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10168
0
    g.NextItemData.Width = item_width;
10169
0
}
10170
10171
// FIXME: Remove the == 0.0f behavior?
10172
void ImGui::PushItemWidth(float item_width)
10173
0
{
10174
0
    ImGuiContext& g = *GImGui;
10175
0
    ImGuiWindow* window = g.CurrentWindow;
10176
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10177
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10178
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10179
0
}
10180
10181
void ImGui::PushMultiItemsWidths(int components, float w_full)
10182
0
{
10183
0
    ImGuiContext& g = *GImGui;
10184
0
    ImGuiWindow* window = g.CurrentWindow;
10185
0
    const ImGuiStyle& style = g.Style;
10186
0
    const float w_item_one  = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
10187
0
    const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
10188
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10189
0
    window->DC.ItemWidthStack.push_back(w_item_last);
10190
0
    for (int i = 0; i < components - 2; i++)
10191
0
        window->DC.ItemWidthStack.push_back(w_item_one);
10192
0
    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
10193
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10194
0
}
10195
10196
void ImGui::PopItemWidth()
10197
0
{
10198
0
    ImGuiWindow* window = GetCurrentWindow();
10199
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10200
0
    window->DC.ItemWidthStack.pop_back();
10201
0
}
10202
10203
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10204
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10205
float ImGui::CalcItemWidth()
10206
0
{
10207
0
    ImGuiContext& g = *GImGui;
10208
0
    ImGuiWindow* window = g.CurrentWindow;
10209
0
    float w;
10210
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10211
0
        w = g.NextItemData.Width;
10212
0
    else
10213
0
        w = window->DC.ItemWidth;
10214
0
    if (w < 0.0f)
10215
0
    {
10216
0
        float region_max_x = GetContentRegionMaxAbs().x;
10217
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10218
0
    }
10219
0
    w = IM_FLOOR(w);
10220
0
    return w;
10221
0
}
10222
10223
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10224
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10225
// Note that only CalcItemWidth() is publicly exposed.
10226
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10227
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10228
0
{
10229
0
    ImGuiContext& g = *GImGui;
10230
0
    ImGuiWindow* window = g.CurrentWindow;
10231
10232
0
    ImVec2 region_max;
10233
0
    if (size.x < 0.0f || size.y < 0.0f)
10234
0
        region_max = GetContentRegionMaxAbs();
10235
10236
0
    if (size.x == 0.0f)
10237
0
        size.x = default_w;
10238
0
    else if (size.x < 0.0f)
10239
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10240
10241
0
    if (size.y == 0.0f)
10242
0
        size.y = default_h;
10243
0
    else if (size.y < 0.0f)
10244
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10245
10246
0
    return size;
10247
0
}
10248
10249
float ImGui::GetTextLineHeight()
10250
59
{
10251
59
    ImGuiContext& g = *GImGui;
10252
59
    return g.FontSize;
10253
59
}
10254
10255
float ImGui::GetTextLineHeightWithSpacing()
10256
103k
{
10257
103k
    ImGuiContext& g = *GImGui;
10258
103k
    return g.FontSize + g.Style.ItemSpacing.y;
10259
103k
}
10260
10261
float ImGui::GetFrameHeight()
10262
185
{
10263
185
    ImGuiContext& g = *GImGui;
10264
185
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10265
185
}
10266
10267
float ImGui::GetFrameHeightWithSpacing()
10268
0
{
10269
0
    ImGuiContext& g = *GImGui;
10270
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10271
0
}
10272
10273
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10274
10275
// FIXME: This is in window space (not screen space!).
10276
ImVec2 ImGui::GetContentRegionMax()
10277
0
{
10278
0
    ImGuiContext& g = *GImGui;
10279
0
    ImGuiWindow* window = g.CurrentWindow;
10280
0
    ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
10281
0
    if (window->DC.CurrentColumns || g.CurrentTable)
10282
0
        mx.x = window->WorkRect.Max.x - window->Pos.x;
10283
0
    return mx;
10284
0
}
10285
10286
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10287
ImVec2 ImGui::GetContentRegionMaxAbs()
10288
103k
{
10289
103k
    ImGuiContext& g = *GImGui;
10290
103k
    ImGuiWindow* window = g.CurrentWindow;
10291
103k
    ImVec2 mx = window->ContentRegionRect.Max;
10292
103k
    if (window->DC.CurrentColumns || g.CurrentTable)
10293
0
        mx.x = window->WorkRect.Max.x;
10294
103k
    return mx;
10295
103k
}
10296
10297
ImVec2 ImGui::GetContentRegionAvail()
10298
103k
{
10299
103k
    ImGuiWindow* window = GImGui->CurrentWindow;
10300
103k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10301
103k
}
10302
10303
// In window space (not screen space!)
10304
ImVec2 ImGui::GetWindowContentRegionMin()
10305
0
{
10306
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10307
0
    return window->ContentRegionRect.Min - window->Pos;
10308
0
}
10309
10310
ImVec2 ImGui::GetWindowContentRegionMax()
10311
103k
{
10312
103k
    ImGuiWindow* window = GImGui->CurrentWindow;
10313
103k
    return window->ContentRegionRect.Max - window->Pos;
10314
103k
}
10315
10316
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10317
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10318
// FIXME-OPT: Could we safely early out on ->SkipItems?
10319
void ImGui::BeginGroup()
10320
0
{
10321
0
    ImGuiContext& g = *GImGui;
10322
0
    ImGuiWindow* window = g.CurrentWindow;
10323
10324
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10325
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10326
0
    group_data.WindowID = window->ID;
10327
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10328
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10329
0
    group_data.BackupIndent = window->DC.Indent;
10330
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10331
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10332
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10333
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10334
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10335
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10336
0
    group_data.EmitItem = true;
10337
10338
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10339
0
    window->DC.Indent = window->DC.GroupOffset;
10340
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10341
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10342
0
    if (g.LogEnabled)
10343
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10344
0
}
10345
10346
void ImGui::EndGroup()
10347
0
{
10348
0
    ImGuiContext& g = *GImGui;
10349
0
    ImGuiWindow* window = g.CurrentWindow;
10350
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10351
10352
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10353
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10354
10355
0
    if (window->DC.IsSetPos)
10356
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10357
10358
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10359
10360
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10361
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10362
0
    window->DC.Indent = group_data.BackupIndent;
10363
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10364
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10365
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10366
0
    if (g.LogEnabled)
10367
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10368
10369
0
    if (!group_data.EmitItem)
10370
0
    {
10371
0
        g.GroupStack.pop_back();
10372
0
        return;
10373
0
    }
10374
10375
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10376
0
    ItemSize(group_bb.GetSize());
10377
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10378
10379
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10380
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10381
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10382
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10383
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10384
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10385
0
    if (group_contains_curr_active_id)
10386
0
        g.LastItemData.ID = g.ActiveId;
10387
0
    else if (group_contains_prev_active_id)
10388
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10389
0
    g.LastItemData.Rect = group_bb;
10390
10391
    // Forward Hovered flag
10392
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10393
0
    if (group_contains_curr_hovered_id)
10394
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10395
10396
    // Forward Edited flag
10397
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10398
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10399
10400
    // Forward Deactivated flag
10401
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10402
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10403
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10404
10405
0
    g.GroupStack.pop_back();
10406
    //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10407
0
}
10408
10409
10410
//-----------------------------------------------------------------------------
10411
// [SECTION] SCROLLING
10412
//-----------------------------------------------------------------------------
10413
10414
// Helper to snap on edges when aiming at an item very close to the edge,
10415
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10416
// When we refactor the scrolling API this may be configurable with a flag?
10417
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10418
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10419
0
{
10420
0
    if (target <= snap_min + snap_threshold)
10421
0
        return ImLerp(snap_min, target, center_ratio);
10422
0
    if (target >= snap_max - snap_threshold)
10423
0
        return ImLerp(target, snap_max, center_ratio);
10424
0
    return target;
10425
0
}
10426
10427
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10428
440k
{
10429
440k
    ImVec2 scroll = window->Scroll;
10430
440k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10431
1.32M
    for (int axis = 0; axis < 2; axis++)
10432
880k
    {
10433
880k
        if (window->ScrollTarget[axis] < FLT_MAX)
10434
65.1k
        {
10435
65.1k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
10436
65.1k
            float scroll_target = window->ScrollTarget[axis];
10437
65.1k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10438
0
            {
10439
0
                float snap_min = 0.0f;
10440
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10441
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10442
0
            }
10443
65.1k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10444
65.1k
        }
10445
880k
        scroll[axis] = IM_FLOOR(ImMax(scroll[axis], 0.0f));
10446
880k
        if (!window->Collapsed && !window->SkipItems)
10447
735k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
10448
880k
    }
10449
440k
    return scroll;
10450
440k
}
10451
10452
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10453
0
{
10454
0
    ImGuiContext& g = *GImGui;
10455
0
    ImGuiWindow* window = g.CurrentWindow;
10456
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10457
0
}
10458
10459
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10460
0
{
10461
0
    ScrollToRectEx(window, item_rect, flags);
10462
0
}
10463
10464
// Scroll to keep newly navigated item fully into view
10465
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10466
44
{
10467
44
    ImGuiContext& g = *GImGui;
10468
44
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10469
44
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
10470
44
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
10471
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10472
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10473
10474
    // Check that only one behavior is selected per axis
10475
44
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10476
44
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10477
10478
    // Defaults
10479
44
    ImGuiScrollFlags in_flags = flags;
10480
44
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10481
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10482
44
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10483
36
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10484
10485
44
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10486
44
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10487
44
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10488
44
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10489
10490
44
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10491
0
    {
10492
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10493
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10494
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
10495
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10496
0
    }
10497
44
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10498
0
    {
10499
0
        if (can_be_fully_visible_x)
10500
0
            SetScrollFromPosX(window, ImFloor((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
10501
0
        else
10502
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
10503
0
    }
10504
10505
44
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10506
0
    {
10507
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10508
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10509
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
10510
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10511
0
    }
10512
44
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10513
0
    {
10514
0
        if (can_be_fully_visible_y)
10515
0
            SetScrollFromPosY(window, ImFloor((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
10516
0
        else
10517
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
10518
0
    }
10519
10520
44
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10521
44
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10522
10523
    // Also scroll parent window to keep us into view if necessary
10524
44
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10525
0
    {
10526
        // FIXME-SCROLL: May be an option?
10527
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10528
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10529
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10530
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10531
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10532
0
    }
10533
10534
44
    return delta_scroll;
10535
44
}
10536
10537
float ImGui::GetScrollX()
10538
147k
{
10539
147k
    ImGuiWindow* window = GImGui->CurrentWindow;
10540
147k
    return window->Scroll.x;
10541
147k
}
10542
10543
float ImGui::GetScrollY()
10544
147k
{
10545
147k
    ImGuiWindow* window = GImGui->CurrentWindow;
10546
147k
    return window->Scroll.y;
10547
147k
}
10548
10549
float ImGui::GetScrollMaxX()
10550
0
{
10551
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10552
0
    return window->ScrollMax.x;
10553
0
}
10554
10555
float ImGui::GetScrollMaxY()
10556
0
{
10557
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10558
0
    return window->ScrollMax.y;
10559
0
}
10560
10561
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10562
25.3k
{
10563
25.3k
    window->ScrollTarget.x = scroll_x;
10564
25.3k
    window->ScrollTargetCenterRatio.x = 0.0f;
10565
25.3k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10566
25.3k
}
10567
10568
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10569
40.4k
{
10570
40.4k
    window->ScrollTarget.y = scroll_y;
10571
40.4k
    window->ScrollTargetCenterRatio.y = 0.0f;
10572
40.4k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10573
40.4k
}
10574
10575
void ImGui::SetScrollX(float scroll_x)
10576
25.2k
{
10577
25.2k
    ImGuiContext& g = *GImGui;
10578
25.2k
    SetScrollX(g.CurrentWindow, scroll_x);
10579
25.2k
}
10580
10581
void ImGui::SetScrollY(float scroll_y)
10582
40.1k
{
10583
40.1k
    ImGuiContext& g = *GImGui;
10584
40.1k
    SetScrollY(g.CurrentWindow, scroll_y);
10585
40.1k
}
10586
10587
// Note that a local position will vary depending on initial scroll value,
10588
// This is a little bit confusing so bear with us:
10589
//  - local_pos = (absolution_pos - window->Pos)
10590
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10591
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10592
//  - They mostly exist because of legacy API.
10593
// Following the rules above, when trying to work with scrolling code, consider that:
10594
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10595
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10596
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10597
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10598
0
{
10599
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10600
0
    window->ScrollTarget.x = IM_FLOOR(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10601
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10602
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10603
0
}
10604
10605
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10606
0
{
10607
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10608
0
    window->ScrollTarget.y = IM_FLOOR(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10609
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10610
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10611
0
}
10612
10613
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10614
0
{
10615
0
    ImGuiContext& g = *GImGui;
10616
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10617
0
}
10618
10619
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10620
0
{
10621
0
    ImGuiContext& g = *GImGui;
10622
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10623
0
}
10624
10625
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10626
void ImGui::SetScrollHereX(float center_x_ratio)
10627
0
{
10628
0
    ImGuiContext& g = *GImGui;
10629
0
    ImGuiWindow* window = g.CurrentWindow;
10630
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10631
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10632
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10633
10634
    // Tweak: snap on edges when aiming at an item very close to the edge
10635
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10636
0
}
10637
10638
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10639
void ImGui::SetScrollHereY(float center_y_ratio)
10640
0
{
10641
0
    ImGuiContext& g = *GImGui;
10642
0
    ImGuiWindow* window = g.CurrentWindow;
10643
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10644
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10645
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10646
10647
    // Tweak: snap on edges when aiming at an item very close to the edge
10648
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10649
0
}
10650
10651
//-----------------------------------------------------------------------------
10652
// [SECTION] TOOLTIPS
10653
//-----------------------------------------------------------------------------
10654
10655
bool ImGui::BeginTooltip()
10656
2.36k
{
10657
2.36k
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10658
2.36k
}
10659
10660
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
10661
2.36k
{
10662
2.36k
    ImGuiContext& g = *GImGui;
10663
10664
2.36k
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
10665
0
    {
10666
        // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
10667
        // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
10668
        // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
10669
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
10670
0
        ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
10671
0
        SetNextWindowPos(tooltip_pos);
10672
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
10673
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
10674
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
10675
0
    }
10676
10677
2.36k
    char window_name[16];
10678
2.36k
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
10679
2.36k
    if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
10680
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
10681
0
            if (window->Active)
10682
0
            {
10683
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
10684
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(window);
10685
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
10686
0
            }
10687
2.36k
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
10688
2.36k
    Begin(window_name, NULL, flags | extra_window_flags);
10689
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
10690
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
10691
    //if (!ret)
10692
    //    End();
10693
    //return ret;
10694
2.36k
    return true;
10695
2.36k
}
10696
10697
void ImGui::EndTooltip()
10698
2.36k
{
10699
2.36k
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
10700
2.36k
    End();
10701
2.36k
}
10702
10703
void ImGui::SetTooltipV(const char* fmt, va_list args)
10704
0
{
10705
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None))
10706
0
        return;
10707
0
    TextV(fmt, args);
10708
0
    EndTooltip();
10709
0
}
10710
10711
void ImGui::SetTooltip(const char* fmt, ...)
10712
0
{
10713
0
    va_list args;
10714
0
    va_start(args, fmt);
10715
0
    SetTooltipV(fmt, args);
10716
0
    va_end(args);
10717
0
}
10718
10719
//-----------------------------------------------------------------------------
10720
// [SECTION] POPUPS
10721
//-----------------------------------------------------------------------------
10722
10723
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
10724
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
10725
0
{
10726
0
    ImGuiContext& g = *GImGui;
10727
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
10728
0
    {
10729
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
10730
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
10731
0
        IM_ASSERT(id == 0);
10732
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10733
0
            return g.OpenPopupStack.Size > 0;
10734
0
        else
10735
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
10736
0
    }
10737
0
    else
10738
0
    {
10739
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10740
0
        {
10741
            // Return true if the popup is open anywhere in the popup stack
10742
0
            for (int n = 0; n < g.OpenPopupStack.Size; n++)
10743
0
                if (g.OpenPopupStack[n].PopupId == id)
10744
0
                    return true;
10745
0
            return false;
10746
0
        }
10747
0
        else
10748
0
        {
10749
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
10750
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
10751
0
        }
10752
0
    }
10753
0
}
10754
10755
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
10756
0
{
10757
0
    ImGuiContext& g = *GImGui;
10758
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
10759
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
10760
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
10761
0
    return IsPopupOpen(id, popup_flags);
10762
0
}
10763
10764
// Also see FindBlockingModal(NULL)
10765
ImGuiWindow* ImGui::GetTopMostPopupModal()
10766
502k
{
10767
502k
    ImGuiContext& g = *GImGui;
10768
502k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10769
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10770
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
10771
0
                return popup;
10772
502k
    return NULL;
10773
502k
}
10774
10775
// See Demo->Stacked Modal to confirm what this is for.
10776
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
10777
167k
{
10778
167k
    ImGuiContext& g = *GImGui;
10779
167k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10780
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10781
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
10782
0
                return popup;
10783
167k
    return NULL;
10784
167k
}
10785
10786
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
10787
0
{
10788
0
    ImGuiContext& g = *GImGui;
10789
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10790
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
10791
0
    OpenPopupEx(id, popup_flags);
10792
0
}
10793
10794
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
10795
0
{
10796
0
    OpenPopupEx(id, popup_flags);
10797
0
}
10798
10799
// Mark popup as open (toggle toward open state).
10800
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
10801
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
10802
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
10803
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
10804
0
{
10805
0
    ImGuiContext& g = *GImGui;
10806
0
    ImGuiWindow* parent_window = g.CurrentWindow;
10807
0
    const int current_stack_size = g.BeginPopupStack.Size;
10808
10809
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
10810
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
10811
0
            return;
10812
10813
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
10814
0
    popup_ref.PopupId = id;
10815
0
    popup_ref.Window = NULL;
10816
0
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
10817
0
    popup_ref.OpenFrameCount = g.FrameCount;
10818
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
10819
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
10820
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
10821
10822
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
10823
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
10824
0
    {
10825
0
        g.OpenPopupStack.push_back(popup_ref);
10826
0
    }
10827
0
    else
10828
0
    {
10829
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
10830
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
10831
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
10832
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
10833
0
        {
10834
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
10835
0
        }
10836
0
        else
10837
0
        {
10838
            // Close child popups if any, then flag popup for open/reopen
10839
0
            ClosePopupToLevel(current_stack_size, false);
10840
0
            g.OpenPopupStack.push_back(popup_ref);
10841
0
        }
10842
10843
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
10844
        // This is equivalent to what ClosePopupToLevel() does.
10845
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
10846
        //    FocusWindow(parent_window);
10847
0
    }
10848
0
}
10849
10850
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
10851
// This function closes any popups that are over 'ref_window'.
10852
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
10853
24.1k
{
10854
24.1k
    ImGuiContext& g = *GImGui;
10855
24.1k
    if (g.OpenPopupStack.Size == 0)
10856
24.1k
        return;
10857
10858
    // Don't close our own child popup windows.
10859
0
    int popup_count_to_keep = 0;
10860
0
    if (ref_window)
10861
0
    {
10862
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
10863
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
10864
0
        {
10865
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
10866
0
            if (!popup.Window)
10867
0
                continue;
10868
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
10869
0
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
10870
0
                continue;
10871
10872
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
10873
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
10874
            //     Window -> Popup1 -> Popup2 -> Popup3
10875
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
10876
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
10877
0
            bool ref_window_is_descendent_of_popup = false;
10878
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
10879
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
10880
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
10881
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
10882
0
                    {
10883
0
                        ref_window_is_descendent_of_popup = true;
10884
0
                        break;
10885
0
                    }
10886
0
            if (!ref_window_is_descendent_of_popup)
10887
0
                break;
10888
0
        }
10889
0
    }
10890
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10891
0
    {
10892
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
10893
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
10894
0
    }
10895
0
}
10896
10897
void ImGui::ClosePopupsExceptModals()
10898
0
{
10899
0
    ImGuiContext& g = *GImGui;
10900
10901
0
    int popup_count_to_keep;
10902
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
10903
0
    {
10904
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
10905
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
10906
0
            break;
10907
0
    }
10908
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10909
0
        ClosePopupToLevel(popup_count_to_keep, true);
10910
0
}
10911
10912
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
10913
0
{
10914
0
    ImGuiContext& g = *GImGui;
10915
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
10916
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
10917
10918
    // Trim open popup stack
10919
0
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
10920
0
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
10921
0
    g.OpenPopupStack.resize(remaining);
10922
10923
0
    if (restore_focus_to_window_under_popup)
10924
0
    {
10925
0
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
10926
0
        if (focus_window && !focus_window->WasActive && popup_window)
10927
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
10928
0
        else
10929
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
10930
0
    }
10931
0
}
10932
10933
// Close the popup we have begin-ed into.
10934
void ImGui::CloseCurrentPopup()
10935
0
{
10936
0
    ImGuiContext& g = *GImGui;
10937
0
    int popup_idx = g.BeginPopupStack.Size - 1;
10938
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
10939
0
        return;
10940
10941
    // Closing a menu closes its top-most parent popup (unless a modal)
10942
0
    while (popup_idx > 0)
10943
0
    {
10944
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
10945
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
10946
0
        bool close_parent = false;
10947
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
10948
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
10949
0
                close_parent = true;
10950
0
        if (!close_parent)
10951
0
            break;
10952
0
        popup_idx--;
10953
0
    }
10954
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
10955
0
    ClosePopupToLevel(popup_idx, true);
10956
10957
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
10958
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
10959
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
10960
0
    if (ImGuiWindow* window = g.NavWindow)
10961
0
        window->DC.NavHideHighlightOneFrame = true;
10962
0
}
10963
10964
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
10965
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
10966
0
{
10967
0
    ImGuiContext& g = *GImGui;
10968
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
10969
0
    {
10970
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10971
0
        return false;
10972
0
    }
10973
10974
0
    char name[20];
10975
0
    if (flags & ImGuiWindowFlags_ChildMenu)
10976
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
10977
0
    else
10978
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
10979
10980
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
10981
0
    bool is_open = Begin(name, NULL, flags);
10982
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
10983
0
        EndPopup();
10984
10985
0
    return is_open;
10986
0
}
10987
10988
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
10989
0
{
10990
0
    ImGuiContext& g = *GImGui;
10991
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
10992
0
    {
10993
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10994
0
        return false;
10995
0
    }
10996
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
10997
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10998
0
    return BeginPopupEx(id, flags);
10999
0
}
11000
11001
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11002
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
11003
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11004
0
{
11005
0
    ImGuiContext& g = *GImGui;
11006
0
    ImGuiWindow* window = g.CurrentWindow;
11007
0
    const ImGuiID id = window->GetID(name);
11008
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11009
0
    {
11010
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11011
0
        return false;
11012
0
    }
11013
11014
    // Center modal windows by default for increased visibility
11015
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11016
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11017
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11018
0
    {
11019
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
11020
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
11021
0
    }
11022
11023
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
11024
0
    const bool is_open = Begin(name, p_open, flags);
11025
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11026
0
    {
11027
0
        EndPopup();
11028
0
        if (is_open)
11029
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
11030
0
        return false;
11031
0
    }
11032
0
    return is_open;
11033
0
}
11034
11035
void ImGui::EndPopup()
11036
0
{
11037
0
    ImGuiContext& g = *GImGui;
11038
0
    ImGuiWindow* window = g.CurrentWindow;
11039
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
11040
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
11041
11042
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
11043
0
    if (g.NavWindow == window)
11044
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
11045
11046
    // Child-popups don't need to be laid out
11047
0
    IM_ASSERT(g.WithinEndChild == false);
11048
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
11049
0
        g.WithinEndChild = true;
11050
0
    End();
11051
0
    g.WithinEndChild = false;
11052
0
}
11053
11054
// Helper to open a popup if mouse button is released over the item
11055
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11056
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11057
0
{
11058
0
    ImGuiContext& g = *GImGui;
11059
0
    ImGuiWindow* window = g.CurrentWindow;
11060
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11061
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11062
0
    {
11063
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11064
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11065
0
        OpenPopupEx(id, popup_flags);
11066
0
    }
11067
0
}
11068
11069
// This is a helper to handle the simplest case of associating one named popup to one given widget.
11070
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11071
// - To create a popup with a specific identifier, pass it in str_id.
11072
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11073
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11074
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11075
//   This is essentially the same as:
11076
//       id = str_id ? GetID(str_id) : GetItemID();
11077
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11078
//       return BeginPopup(id);
11079
//   Which is essentially the same as:
11080
//       id = str_id ? GetID(str_id) : GetItemID();
11081
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11082
//           OpenPopup(id);
11083
//       return BeginPopup(id);
11084
//   The main difference being that this is tweaked to avoid computing the ID twice.
11085
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11086
0
{
11087
0
    ImGuiContext& g = *GImGui;
11088
0
    ImGuiWindow* window = g.CurrentWindow;
11089
0
    if (window->SkipItems)
11090
0
        return false;
11091
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11092
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11093
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11094
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11095
0
        OpenPopupEx(id, popup_flags);
11096
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11097
0
}
11098
11099
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11100
0
{
11101
0
    ImGuiContext& g = *GImGui;
11102
0
    ImGuiWindow* window = g.CurrentWindow;
11103
0
    if (!str_id)
11104
0
        str_id = "window_context";
11105
0
    ImGuiID id = window->GetID(str_id);
11106
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11107
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11108
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11109
0
            OpenPopupEx(id, popup_flags);
11110
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11111
0
}
11112
11113
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11114
0
{
11115
0
    ImGuiContext& g = *GImGui;
11116
0
    ImGuiWindow* window = g.CurrentWindow;
11117
0
    if (!str_id)
11118
0
        str_id = "void_context";
11119
0
    ImGuiID id = window->GetID(str_id);
11120
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11121
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11122
0
        if (GetTopMostPopupModal() == NULL)
11123
0
            OpenPopupEx(id, popup_flags);
11124
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11125
0
}
11126
11127
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
11128
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
11129
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11130
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11131
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
11132
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11133
2.36k
{
11134
2.36k
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
11135
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11136
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11137
11138
    // Combo Box policy (we want a connecting edge)
11139
2.36k
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
11140
0
    {
11141
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11142
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11143
0
        {
11144
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11145
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11146
0
                continue;
11147
0
            ImVec2 pos;
11148
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
11149
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11150
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11151
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11152
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
11153
0
                continue;
11154
0
            *last_dir = dir;
11155
0
            return pos;
11156
0
        }
11157
0
    }
11158
11159
    // Tooltip and Default popup policy
11160
    // (Always first try the direction we used on the last frame, if any)
11161
2.36k
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11162
2.36k
    {
11163
2.36k
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11164
2.38k
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11165
2.38k
        {
11166
2.38k
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11167
2.38k
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11168
6
                continue;
11169
11170
2.37k
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11171
2.37k
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11172
11173
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11174
2.37k
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11175
12
                continue;
11176
2.36k
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11177
8
                continue;
11178
11179
2.35k
            ImVec2 pos;
11180
2.35k
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11181
2.35k
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11182
11183
            // Clamp top-left corner of popup
11184
2.35k
            pos.x = ImMax(pos.x, r_outer.Min.x);
11185
2.35k
            pos.y = ImMax(pos.y, r_outer.Min.y);
11186
11187
2.35k
            *last_dir = dir;
11188
2.35k
            return pos;
11189
2.36k
        }
11190
2.36k
    }
11191
11192
    // Fallback when not enough room:
11193
4
    *last_dir = ImGuiDir_None;
11194
11195
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11196
4
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11197
4
        return ref_pos + ImVec2(2, 2);
11198
11199
    // Otherwise try to keep within display
11200
0
    ImVec2 pos = ref_pos;
11201
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11202
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11203
0
    return pos;
11204
4
}
11205
11206
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11207
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11208
2.36k
{
11209
2.36k
    ImGuiContext& g = *GImGui;
11210
2.36k
    ImRect r_screen;
11211
2.36k
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11212
0
    {
11213
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11214
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11215
0
        r_screen.Min = monitor.WorkPos;
11216
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11217
0
    }
11218
2.36k
    else
11219
2.36k
    {
11220
        // Use the full viewport area (not work area) for popups
11221
2.36k
        r_screen = window->Viewport->GetMainRect();
11222
2.36k
    }
11223
2.36k
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11224
2.36k
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11225
2.36k
    return r_screen;
11226
2.36k
}
11227
11228
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11229
2.36k
{
11230
2.36k
    ImGuiContext& g = *GImGui;
11231
11232
2.36k
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11233
2.36k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11234
0
    {
11235
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11236
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11237
0
        ImGuiWindow* parent_window = window->ParentWindow;
11238
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11239
0
        ImRect r_avoid;
11240
0
        if (parent_window->DC.MenuBarAppending)
11241
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11242
0
        else
11243
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11244
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11245
0
    }
11246
2.36k
    if (window->Flags & ImGuiWindowFlags_Popup)
11247
0
    {
11248
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11249
0
    }
11250
2.36k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11251
2.36k
    {
11252
        // Position tooltip (always follows mouse)
11253
2.36k
        float sc = g.Style.MouseCursorScale;
11254
2.36k
        ImVec2 ref_pos = NavCalcPreferredRefPos();
11255
2.36k
        ImRect r_avoid;
11256
2.36k
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11257
96
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11258
2.26k
        else
11259
2.26k
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11260
2.36k
        return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11261
2.36k
    }
11262
0
    IM_ASSERT(0);
11263
0
    return window->Pos;
11264
2.36k
}
11265
11266
//-----------------------------------------------------------------------------
11267
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11268
//-----------------------------------------------------------------------------
11269
11270
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11271
// In our terminology those should be interchangeable, yet right now this is super confusing.
11272
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11273
11274
void ImGui::SetNavWindow(ImGuiWindow* window)
11275
23.1k
{
11276
23.1k
    ImGuiContext& g = *GImGui;
11277
23.1k
    if (g.NavWindow != window)
11278
23.1k
    {
11279
23.1k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11280
23.1k
        g.NavWindow = window;
11281
23.1k
    }
11282
23.1k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11283
23.1k
    NavUpdateAnyRequestFlag();
11284
23.1k
}
11285
11286
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
11287
9.58k
{
11288
9.58k
    ImGuiContext& g = *GImGui;
11289
9.58k
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
11290
9.58k
}
11291
11292
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11293
768
{
11294
768
    ImGuiContext& g = *GImGui;
11295
768
    IM_ASSERT(g.NavWindow != NULL);
11296
768
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11297
768
    g.NavId = id;
11298
768
    g.NavLayer = nav_layer;
11299
768
    g.NavFocusScopeId = focus_scope_id;
11300
768
    g.NavWindow->NavLastIds[nav_layer] = id;
11301
768
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11302
11303
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11304
768
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11305
768
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11306
768
}
11307
11308
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11309
6
{
11310
6
    ImGuiContext& g = *GImGui;
11311
6
    IM_ASSERT(id != 0);
11312
11313
6
    if (g.NavWindow != window)
11314
6
       SetNavWindow(window);
11315
11316
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11317
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11318
6
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11319
6
    g.NavId = id;
11320
6
    g.NavLayer = nav_layer;
11321
6
    g.NavFocusScopeId = g.CurrentFocusScopeId;
11322
6
    window->NavLastIds[nav_layer] = id;
11323
6
    if (g.LastItemData.ID == id)
11324
6
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11325
11326
6
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
11327
0
        g.NavDisableMouseHover = true;
11328
6
    else
11329
6
        g.NavDisableHighlight = true;
11330
11331
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11332
6
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11333
6
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11334
6
}
11335
11336
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11337
80
{
11338
80
    if (ImFabs(dx) > ImFabs(dy))
11339
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11340
80
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11341
80
}
11342
11343
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
11344
160
{
11345
160
    if (cand_max < curr_min)
11346
4
        return cand_max - curr_min;
11347
156
    if (curr_max < cand_min)
11348
76
        return cand_min - curr_max;
11349
80
    return 0.0f;
11350
156
}
11351
11352
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11353
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11354
1.41k
{
11355
1.41k
    ImGuiContext& g = *GImGui;
11356
1.41k
    ImGuiWindow* window = g.CurrentWindow;
11357
1.41k
    if (g.NavLayer != window->DC.NavLayerCurrent)
11358
1.33k
        return false;
11359
11360
    // FIXME: Those are not good variables names
11361
80
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11362
80
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11363
80
    g.NavScoringDebugCount++;
11364
11365
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11366
80
    if (window->ParentWindow == g.NavWindow)
11367
0
    {
11368
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11369
0
        if (!window->ClipRect.Overlaps(cand))
11370
0
            return false;
11371
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11372
0
    }
11373
11374
    // Compute distance between boxes
11375
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11376
80
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11377
80
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11378
80
    if (dby != 0.0f && dbx != 0.0f)
11379
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11380
80
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11381
11382
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11383
80
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11384
80
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11385
80
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11386
11387
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11388
80
    ImGuiDir quadrant;
11389
80
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11390
80
    if (dbx != 0.0f || dby != 0.0f)
11391
80
    {
11392
        // For non-overlapping boxes, use distance between boxes
11393
80
        dax = dbx;
11394
80
        day = dby;
11395
80
        dist_axial = dist_box;
11396
80
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11397
80
    }
11398
0
    else if (dcx != 0.0f || dcy != 0.0f)
11399
0
    {
11400
        // For overlapping boxes with different centers, use distance between centers
11401
0
        dax = dcx;
11402
0
        day = dcy;
11403
0
        dist_axial = dist_center;
11404
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11405
0
    }
11406
0
    else
11407
0
    {
11408
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11409
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11410
0
    }
11411
11412
80
    const ImGuiDir move_dir = g.NavMoveDir;
11413
#if IMGUI_DEBUG_NAV_SCORING
11414
    char buf[200];
11415
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
11416
    {
11417
        if (quadrant == move_dir)
11418
        {
11419
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11420
            ImDrawList* draw_list = GetForegroundDrawList(window);
11421
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
11422
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
11423
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11424
        }
11425
    }
11426
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
11427
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
11428
    if (debug_hovering || debug_tty)
11429
    {
11430
        ImFormatString(buf, IM_ARRAYSIZE(buf),
11431
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
11432
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
11433
        if (debug_hovering)
11434
        {
11435
            ImDrawList* draw_list = GetForegroundDrawList(window);
11436
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
11437
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
11438
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
11439
            draw_list->AddText(cand.Max, ~0U, buf);
11440
        }
11441
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
11442
    }
11443
#endif
11444
11445
    // Is it in the quadrant we're interested in moving to?
11446
80
    bool new_best = false;
11447
80
    if (quadrant == move_dir)
11448
80
    {
11449
        // Does it beat the current best candidate?
11450
80
        if (dist_box < result->DistBox)
11451
80
        {
11452
80
            result->DistBox = dist_box;
11453
80
            result->DistCenter = dist_center;
11454
80
            return true;
11455
80
        }
11456
0
        if (dist_box == result->DistBox)
11457
0
        {
11458
            // Try using distance between center points to break ties
11459
0
            if (dist_center < result->DistCenter)
11460
0
            {
11461
0
                result->DistCenter = dist_center;
11462
0
                new_best = true;
11463
0
            }
11464
0
            else if (dist_center == result->DistCenter)
11465
0
            {
11466
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11467
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11468
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11469
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11470
0
                    new_best = true;
11471
0
            }
11472
0
        }
11473
0
    }
11474
11475
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11476
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11477
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11478
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11479
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11480
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11481
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11482
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11483
0
            {
11484
0
                result->DistAxial = dist_axial;
11485
0
                new_best = true;
11486
0
            }
11487
11488
0
    return new_best;
11489
80
}
11490
11491
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11492
99
{
11493
99
    ImGuiContext& g = *GImGui;
11494
99
    ImGuiWindow* window = g.CurrentWindow;
11495
99
    result->Window = window;
11496
99
    result->ID = g.LastItemData.ID;
11497
99
    result->FocusScopeId = g.CurrentFocusScopeId;
11498
99
    result->InFlags = g.LastItemData.InFlags;
11499
99
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11500
99
}
11501
11502
// True when current work location may be scrolled horizontally when moving left / right.
11503
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
11504
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
11505
712k
{
11506
712k
    ImGuiContext& g = *GImGui;
11507
712k
    ImGuiWindow* window = g.CurrentWindow;
11508
712k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
11509
712k
}
11510
11511
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11512
// This is called after LastItemData is set.
11513
static void ImGui::NavProcessItem()
11514
1.84k
{
11515
1.84k
    ImGuiContext& g = *GImGui;
11516
1.84k
    ImGuiWindow* window = g.CurrentWindow;
11517
1.84k
    const ImGuiID id = g.LastItemData.ID;
11518
1.84k
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11519
11520
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
11521
1.84k
    if (window->DC.NavIsScrollPushableX == false)
11522
0
    {
11523
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11524
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11525
0
    }
11526
1.84k
    const ImRect nav_bb = g.LastItemData.NavRect;
11527
11528
    // Process Init Request
11529
1.84k
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11530
17
    {
11531
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11532
17
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11533
17
        if (candidate_for_nav_default_focus || g.NavInitResultId == 0)
11534
17
        {
11535
17
            g.NavInitResultId = id;
11536
17
            g.NavInitResultRectRel = WindowRectAbsToRel(window, nav_bb);
11537
17
        }
11538
17
        if (candidate_for_nav_default_focus)
11539
17
        {
11540
17
            g.NavInitRequest = false; // Found a match, clear request
11541
17
            NavUpdateAnyRequestFlag();
11542
17
        }
11543
17
    }
11544
11545
    // Process Move Request (scoring for navigation)
11546
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11547
1.84k
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
11548
1.38k
    {
11549
1.38k
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0;
11550
1.38k
        if (is_tabbing)
11551
174
        {
11552
174
            NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
11553
174
        }
11554
1.21k
        else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
11555
1.19k
        {
11556
1.19k
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11557
1.19k
            if (NavScoreItem(result))
11558
41
                NavApplyItemToResult(result);
11559
11560
            // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11561
1.19k
            const float VISIBLE_RATIO = 0.70f;
11562
1.19k
            if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11563
225
                if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11564
225
                    if (NavScoreItem(&g.NavMoveResultLocalVisible))
11565
39
                        NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11566
1.19k
        }
11567
1.38k
    }
11568
11569
    // Update information for currently focused/navigated item
11570
1.84k
    if (g.NavId == id)
11571
507
    {
11572
507
        if (g.NavWindow != window)
11573
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11574
507
        g.NavLayer = window->DC.NavLayerCurrent;
11575
507
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11576
507
        g.NavIdIsAlive = true;
11577
507
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
11578
507
    }
11579
1.84k
}
11580
11581
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11582
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11583
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11584
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11585
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11586
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11587
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11588
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
11589
174
{
11590
174
    ImGuiContext& g = *GImGui;
11591
11592
174
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
11593
174
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
11594
155
            return;
11595
11596
    // - Can always land on an item when using API call.
11597
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
11598
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
11599
19
    bool can_stop;
11600
19
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
11601
0
        can_stop = true;
11602
19
    else
11603
19
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
11604
11605
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11606
19
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
11607
19
    if (g.NavTabbingDir == +1)
11608
19
    {
11609
        // Tab Forward or SetKeyboardFocusHere() with >= 0
11610
19
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
11611
19
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11612
19
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
11613
0
            NavMoveRequestResolveWithLastItem(result);
11614
19
        else if (g.NavId == id)
11615
15
            g.NavTabbingCounter = 1;
11616
19
    }
11617
0
    else if (g.NavTabbingDir == -1)
11618
0
    {
11619
        // Tab Backward
11620
0
        if (g.NavId == id)
11621
0
        {
11622
0
            if (result->ID)
11623
0
            {
11624
0
                g.NavMoveScoringItems = false;
11625
0
                NavUpdateAnyRequestFlag();
11626
0
            }
11627
0
        }
11628
0
        else if (can_stop)
11629
0
        {
11630
            // Keep applying until reaching NavId
11631
0
            NavApplyItemToResult(result);
11632
0
        }
11633
0
    }
11634
0
    else if (g.NavTabbingDir == 0)
11635
0
    {
11636
0
        if (can_stop && g.NavId == id)
11637
0
            NavMoveRequestResolveWithLastItem(result);
11638
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
11639
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11640
0
    }
11641
19
}
11642
11643
bool ImGui::NavMoveRequestButNoResultYet()
11644
88.0k
{
11645
88.0k
    ImGuiContext& g = *GImGui;
11646
88.0k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
11647
88.0k
}
11648
11649
// FIXME: ScoringRect is not set
11650
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11651
8.58k
{
11652
8.58k
    ImGuiContext& g = *GImGui;
11653
8.58k
    IM_ASSERT(g.NavWindow != NULL);
11654
11655
8.58k
    if (move_flags & ImGuiNavMoveFlags_Tabbing)
11656
2.54k
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
11657
11658
8.58k
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
11659
8.58k
    g.NavMoveDir = move_dir;
11660
8.58k
    g.NavMoveDirForDebug = move_dir;
11661
8.58k
    g.NavMoveClipDir = clip_dir;
11662
8.58k
    g.NavMoveFlags = move_flags;
11663
8.58k
    g.NavMoveScrollFlags = scroll_flags;
11664
8.58k
    g.NavMoveForwardToNextFrame = false;
11665
8.58k
    g.NavMoveKeyMods = g.IO.KeyMods;
11666
8.58k
    g.NavMoveResultLocal.Clear();
11667
8.58k
    g.NavMoveResultLocalVisible.Clear();
11668
8.58k
    g.NavMoveResultOther.Clear();
11669
8.58k
    g.NavTabbingCounter = 0;
11670
8.58k
    g.NavTabbingResultFirst.Clear();
11671
8.58k
    NavUpdateAnyRequestFlag();
11672
8.58k
}
11673
11674
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
11675
0
{
11676
0
    ImGuiContext& g = *GImGui;
11677
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
11678
0
    NavApplyItemToResult(result);
11679
0
    NavUpdateAnyRequestFlag();
11680
0
}
11681
11682
void ImGui::NavMoveRequestCancel()
11683
1.28k
{
11684
1.28k
    ImGuiContext& g = *GImGui;
11685
1.28k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11686
1.28k
    NavUpdateAnyRequestFlag();
11687
1.28k
}
11688
11689
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
11690
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11691
0
{
11692
0
    ImGuiContext& g = *GImGui;
11693
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
11694
0
    NavMoveRequestCancel();
11695
0
    g.NavMoveForwardToNextFrame = true;
11696
0
    g.NavMoveDir = move_dir;
11697
0
    g.NavMoveClipDir = clip_dir;
11698
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
11699
0
    g.NavMoveScrollFlags = scroll_flags;
11700
0
}
11701
11702
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
11703
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
11704
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
11705
0
{
11706
0
    ImGuiContext& g = *GImGui;
11707
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
11708
11709
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it, NavEndFrame() will do the same test
11710
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
11711
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
11712
0
}
11713
11714
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
11715
// This way we could find the last focused window among our children. It would be much less confusing this way?
11716
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
11717
77.4k
{
11718
77.4k
    ImGuiWindow* parent = nav_window;
11719
148k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
11720
70.9k
        parent = parent->ParentWindow;
11721
77.4k
    if (parent && parent != nav_window)
11722
70.9k
        parent->NavLastChildNavWindow = nav_window;
11723
77.4k
}
11724
11725
// Restore the last focused child.
11726
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
11727
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
11728
0
{
11729
0
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
11730
0
        return window->NavLastChildNavWindow;
11731
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
11732
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
11733
0
            return tab->Window;
11734
0
    return window;
11735
0
}
11736
11737
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
11738
0
{
11739
0
    ImGuiContext& g = *GImGui;
11740
0
    if (layer == ImGuiNavLayer_Main)
11741
0
    {
11742
0
        ImGuiWindow* prev_nav_window = g.NavWindow;
11743
0
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
11744
0
        if (prev_nav_window)
11745
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
11746
0
    }
11747
0
    ImGuiWindow* window = g.NavWindow;
11748
0
    if (window->NavLastIds[layer] != 0)
11749
0
    {
11750
0
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
11751
0
    }
11752
0
    else
11753
0
    {
11754
0
        g.NavLayer = layer;
11755
0
        NavInitWindow(window, true);
11756
0
    }
11757
0
}
11758
11759
void ImGui::NavRestoreHighlightAfterMove()
11760
1.45k
{
11761
1.45k
    ImGuiContext& g = *GImGui;
11762
1.45k
    g.NavDisableHighlight = false;
11763
1.45k
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
11764
1.45k
}
11765
11766
static inline void ImGui::NavUpdateAnyRequestFlag()
11767
200k
{
11768
200k
    ImGuiContext& g = *GImGui;
11769
200k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
11770
200k
    if (g.NavAnyRequest)
11771
200k
        IM_ASSERT(g.NavWindow != NULL);
11772
200k
}
11773
11774
// This needs to be called before we submit any widget (aka in or before Begin)
11775
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
11776
12
{
11777
    // FIXME: ChildWindow test here is wrong for docking
11778
12
    ImGuiContext& g = *GImGui;
11779
12
    IM_ASSERT(window == g.NavWindow);
11780
11781
12
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
11782
0
    {
11783
0
        g.NavId = 0;
11784
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11785
0
        return;
11786
0
    }
11787
11788
12
    bool init_for_nav = false;
11789
12
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
11790
12
        init_for_nav = true;
11791
12
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
11792
12
    if (init_for_nav)
11793
12
    {
11794
12
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
11795
12
        g.NavInitRequest = true;
11796
12
        g.NavInitRequestFromMove = false;
11797
12
        g.NavInitResultId = 0;
11798
12
        g.NavInitResultRectRel = ImRect();
11799
12
        NavUpdateAnyRequestFlag();
11800
12
    }
11801
0
    else
11802
0
    {
11803
0
        g.NavId = window->NavLastIds[0];
11804
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11805
0
    }
11806
12
}
11807
11808
static ImVec2 ImGui::NavCalcPreferredRefPos()
11809
2.36k
{
11810
2.36k
    ImGuiContext& g = *GImGui;
11811
2.36k
    ImGuiWindow* window = g.NavWindow;
11812
2.36k
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
11813
2.27k
    {
11814
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
11815
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
11816
        // In theory we could move that +1.0f offset in OpenPopupEx()
11817
2.27k
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
11818
2.27k
        return ImVec2(p.x + 1.0f, p.y);
11819
2.27k
    }
11820
86
    else
11821
86
    {
11822
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
11823
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
11824
86
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
11825
86
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
11826
0
        {
11827
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11828
0
            rect_rel.Translate(window->Scroll - next_scroll);
11829
0
        }
11830
86
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
11831
86
        ImGuiViewport* viewport = window->Viewport;
11832
86
        return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
11833
86
    }
11834
2.36k
}
11835
11836
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
11837
0
{
11838
0
    ImGuiContext& g = *GImGui;
11839
0
    float repeat_delay, repeat_rate;
11840
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
11841
11842
0
    ImGuiKey key_less, key_more;
11843
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
11844
0
    {
11845
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
11846
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
11847
0
    }
11848
0
    else
11849
0
    {
11850
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
11851
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
11852
0
    }
11853
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
11854
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
11855
0
        amount = 0.0f;
11856
0
    return amount;
11857
0
}
11858
11859
static void ImGui::NavUpdate()
11860
167k
{
11861
167k
    ImGuiContext& g = *GImGui;
11862
167k
    ImGuiIO& io = g.IO;
11863
11864
167k
    io.WantSetMousePos = false;
11865
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
11866
11867
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
11868
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
11869
167k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11870
167k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
11871
167k
    if (nav_gamepad_active)
11872
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
11873
0
            if (IsKeyDown(key))
11874
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
11875
167k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11876
167k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
11877
167k
    if (nav_keyboard_active)
11878
167k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
11879
1.16M
            if (IsKeyDown(key))
11880
47.8k
                g.NavInputSource = ImGuiInputSource_Keyboard;
11881
11882
    // Process navigation init request (select first/default focus)
11883
167k
    if (g.NavInitResultId != 0)
11884
17
        NavInitRequestApplyResult();
11885
167k
    g.NavInitRequest = false;
11886
167k
    g.NavInitRequestFromMove = false;
11887
167k
    g.NavInitResultId = 0;
11888
167k
    g.NavJustMovedToId = 0;
11889
11890
    // Process navigation move request
11891
167k
    if (g.NavMoveSubmitted)
11892
8.07k
        NavMoveRequestApplyResult();
11893
167k
    g.NavTabbingCounter = 0;
11894
167k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11895
11896
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
11897
167k
    bool set_mouse_pos = false;
11898
167k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
11899
292
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
11900
292
            set_mouse_pos = true;
11901
167k
    g.NavMousePosDirty = false;
11902
167k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
11903
11904
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
11905
167k
    if (g.NavWindow)
11906
77.4k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
11907
167k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
11908
712
        g.NavWindow->NavLastChildNavWindow = NULL;
11909
11910
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
11911
167k
    NavUpdateWindowing();
11912
11913
    // Set output flags for user application
11914
167k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
11915
167k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
11916
11917
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
11918
167k
    NavUpdateCancelRequest();
11919
11920
    // Process manual activation request
11921
167k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
11922
167k
    g.NavActivateFlags = ImGuiActivateFlags_None;
11923
167k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11924
5.05k
    {
11925
5.05k
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
11926
5.05k
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
11927
5.05k
        const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
11928
5.05k
        const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
11929
5.05k
        if (g.ActiveId == 0 && activate_pressed)
11930
32
        {
11931
32
            g.NavActivateId = g.NavId;
11932
32
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
11933
32
        }
11934
5.05k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
11935
2
        {
11936
2
            g.NavActivateId = g.NavId;
11937
2
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
11938
2
        }
11939
5.05k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
11940
275
            g.NavActivateDownId = g.NavId;
11941
5.05k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
11942
34
            g.NavActivatePressedId = g.NavId;
11943
5.05k
    }
11944
167k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11945
0
        g.NavDisableHighlight = true;
11946
167k
    if (g.NavActivateId != 0)
11947
167k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
11948
11949
    // Process programmatic activation request
11950
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
11951
167k
    if (g.NavNextActivateId != 0)
11952
0
    {
11953
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
11954
0
        g.NavActivateFlags = g.NavNextActivateFlags;
11955
0
    }
11956
167k
    g.NavNextActivateId = 0;
11957
11958
    // Process move requests
11959
167k
    NavUpdateCreateMoveRequest();
11960
167k
    if (g.NavMoveDir == ImGuiDir_None)
11961
161k
        NavUpdateCreateTabbingRequest();
11962
167k
    NavUpdateAnyRequestFlag();
11963
167k
    g.NavIdIsAlive = false;
11964
11965
    // Scrolling
11966
167k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
11967
77.4k
    {
11968
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
11969
77.4k
        ImGuiWindow* window = g.NavWindow;
11970
77.4k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
11971
77.4k
        const ImGuiDir move_dir = g.NavMoveDir;
11972
77.4k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
11973
256
        {
11974
256
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
11975
99
                SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
11976
256
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
11977
157
                SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
11978
256
        }
11979
11980
        // *Normal* Manual scroll with LStick
11981
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
11982
77.4k
        if (nav_gamepad_active)
11983
0
        {
11984
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
11985
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
11986
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
11987
0
                SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
11988
0
            if (scroll_dir.y != 0.0f)
11989
0
                SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
11990
0
        }
11991
77.4k
    }
11992
11993
    // Always prioritize mouse highlight if navigation is disabled
11994
167k
    if (!nav_keyboard_active && !nav_gamepad_active)
11995
0
    {
11996
0
        g.NavDisableHighlight = true;
11997
0
        g.NavDisableMouseHover = set_mouse_pos = false;
11998
0
    }
11999
12000
    // Update mouse position if requested
12001
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
12002
167k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12003
0
    {
12004
0
        io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
12005
0
        io.WantSetMousePos = true;
12006
        //IMGUI_DEBUG_LOG_IO("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
12007
0
    }
12008
12009
    // [DEBUG]
12010
167k
    g.NavScoringDebugCount = 0;
12011
#if IMGUI_DEBUG_NAV_RECTS
12012
    if (ImGuiWindow* debug_window = g.NavWindow)
12013
    {
12014
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12015
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
12016
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
12017
    }
12018
#endif
12019
167k
}
12020
12021
void ImGui::NavInitRequestApplyResult()
12022
17
{
12023
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
12024
17
    ImGuiContext& g = *GImGui;
12025
17
    if (!g.NavWindow)
12026
5
        return;
12027
12028
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12029
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12030
12
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
12031
12
    SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
12032
12
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12033
12
    if (g.NavInitRequestFromMove)
12034
12
        NavRestoreHighlightAfterMove();
12035
12
}
12036
12037
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12038
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir)
12039
6.03k
{
12040
    // Bias initial rect
12041
6.03k
    ImGuiContext& g = *GImGui;
12042
6.03k
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12043
12044
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12045
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12046
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
12047
6.03k
    if (preferred_pos_rel.x == FLT_MAX)
12048
2.92k
        preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
12049
6.03k
    if (preferred_pos_rel.y == FLT_MAX)
12050
4.02k
        preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12051
12052
    // Apply general bias on the other axis
12053
6.03k
    if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12054
4.13k
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12055
1.90k
    else
12056
1.90k
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12057
6.03k
}
12058
12059
void ImGui::NavUpdateCreateMoveRequest()
12060
167k
{
12061
167k
    ImGuiContext& g = *GImGui;
12062
167k
    ImGuiIO& io = g.IO;
12063
167k
    ImGuiWindow* window = g.NavWindow;
12064
167k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12065
167k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12066
12067
167k
    if (g.NavMoveForwardToNextFrame && window != NULL)
12068
0
    {
12069
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
12070
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
12071
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12072
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12073
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12074
0
    }
12075
167k
    else
12076
167k
    {
12077
        // Initiate directional inputs request
12078
167k
        g.NavMoveDir = ImGuiDir_None;
12079
167k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
12080
167k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12081
167k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12082
77.4k
        {
12083
77.4k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
12084
77.4k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
12085
77.4k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
12086
77.4k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
12087
77.4k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
12088
77.4k
        }
12089
167k
        g.NavMoveClipDir = g.NavMoveDir;
12090
167k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12091
167k
    }
12092
12093
    // Update PageUp/PageDown/Home/End scroll
12094
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12095
167k
    float scoring_rect_offset_y = 0.0f;
12096
167k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12097
73.9k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
12098
167k
    if (scoring_rect_offset_y != 0.0f)
12099
2.00k
    {
12100
2.00k
        g.NavScoringNoClipRect = window->InnerRect;
12101
2.00k
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
12102
2.00k
    }
12103
12104
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12105
#if IMGUI_DEBUG_NAV_SCORING
12106
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12107
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12108
    if (io.KeyCtrl)
12109
    {
12110
        if (g.NavMoveDir == ImGuiDir_None)
12111
            g.NavMoveDir = g.NavMoveDirForDebug;
12112
        g.NavMoveClipDir = g.NavMoveDir;
12113
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12114
    }
12115
#endif
12116
12117
    // Submit
12118
167k
    g.NavMoveForwardToNextFrame = false;
12119
167k
    if (g.NavMoveDir != ImGuiDir_None)
12120
6.03k
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
12121
12122
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12123
167k
    if (g.NavMoveSubmitted && g.NavId == 0)
12124
5.24k
    {
12125
5.24k
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12126
5.24k
        g.NavInitRequest = g.NavInitRequestFromMove = true;
12127
5.24k
        g.NavInitResultId = 0;
12128
5.24k
        g.NavDisableHighlight = false;
12129
5.24k
    }
12130
12131
    // When using gamepad, we project the reference nav bounding box into window visible area.
12132
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12133
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12134
167k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12135
0
    {
12136
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12137
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12138
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12139
12140
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12141
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
12142
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12143
12144
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
12145
0
        {
12146
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12147
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
12148
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12149
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12150
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12151
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12152
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12153
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
12154
0
            g.NavId = 0;
12155
0
        }
12156
0
    }
12157
12158
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
12159
167k
    ImRect scoring_rect;
12160
167k
    if (window != NULL)
12161
77.4k
    {
12162
77.4k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12163
77.4k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
12164
77.4k
        scoring_rect.TranslateY(scoring_rect_offset_y);
12165
77.4k
        if (g.NavMoveSubmitted)
12166
6.03k
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir);
12167
77.4k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12168
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12169
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12170
77.4k
    }
12171
167k
    g.NavScoringRect = scoring_rect;
12172
167k
    g.NavScoringNoClipRect.Add(scoring_rect);
12173
167k
}
12174
12175
void ImGui::NavUpdateCreateTabbingRequest()
12176
161k
{
12177
161k
    ImGuiContext& g = *GImGui;
12178
161k
    ImGuiWindow* window = g.NavWindow;
12179
161k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12180
161k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12181
89.6k
        return;
12182
12183
71.4k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12184
71.4k
    if (!tab_pressed)
12185
68.8k
        return;
12186
12187
    // Initiate tabbing request
12188
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12189
    // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests.
12190
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12191
2.54k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12192
2.54k
    if (nav_keyboard_active)
12193
2.54k
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12194
0
    else
12195
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12196
2.54k
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12197
2.54k
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12198
2.54k
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, ImGuiNavMoveFlags_Tabbing, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12199
2.54k
    g.NavTabbingCounter = -1;
12200
2.54k
}
12201
12202
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12203
void ImGui::NavMoveRequestApplyResult()
12204
8.07k
{
12205
8.07k
    ImGuiContext& g = *GImGui;
12206
#if IMGUI_DEBUG_NAV_SCORING
12207
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12208
        return;
12209
#endif
12210
12211
    // Select which result to use
12212
8.07k
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12213
12214
    // Tabbing forward wrap
12215
8.07k
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && result == NULL)
12216
2.40k
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12217
8
            result = &g.NavTabbingResultFirst;
12218
12219
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
12220
8.07k
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12221
8.07k
    if (result == NULL)
12222
8.03k
    {
12223
8.03k
        if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
12224
2.39k
            g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
12225
8.03k
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
12226
702
            NavRestoreHighlightAfterMove();
12227
8.03k
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12228
8.03k
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12229
8.03k
        return;
12230
8.03k
    }
12231
12232
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12233
44
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12234
36
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12235
0
            result = &g.NavMoveResultLocalVisible;
12236
12237
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12238
44
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12239
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12240
0
            result = &g.NavMoveResultOther;
12241
44
    IM_ASSERT(g.NavWindow && result->Window);
12242
12243
    // Scroll to keep newly navigated item fully into view.
12244
44
    if (g.NavLayer == ImGuiNavLayer_Main)
12245
44
    {
12246
44
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12247
44
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12248
12249
44
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12250
0
        {
12251
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
12252
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12253
0
            SetScrollY(result->Window, scroll_target);
12254
0
        }
12255
44
    }
12256
12257
44
    if (g.NavWindow != result->Window)
12258
0
    {
12259
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12260
0
        g.NavWindow = result->Window;
12261
0
    }
12262
44
    if (g.ActiveId != result->ID)
12263
44
        ClearActiveID();
12264
44
    if (g.NavId != result->ID)
12265
0
    {
12266
        // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12267
0
        g.NavJustMovedToId = result->ID;
12268
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12269
0
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12270
0
    }
12271
12272
    // Apply new NavID/Focus
12273
44
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12274
44
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
12275
44
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12276
12277
    // Restore last preferred position for current axis
12278
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
12279
44
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) == 0)
12280
36
    {
12281
36
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
12282
36
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
12283
36
    }
12284
12285
    // Tabbing: Activates Inputable or Focus non-Inputable
12286
44
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable))
12287
0
    {
12288
0
        g.NavNextActivateId = result->ID;
12289
0
        g.NavNextActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
12290
0
        g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
12291
0
    }
12292
12293
    // Activate
12294
44
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12295
0
    {
12296
0
        g.NavNextActivateId = result->ID;
12297
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
12298
0
    }
12299
12300
    // Enable nav highlight
12301
44
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
12302
44
        NavRestoreHighlightAfterMove();
12303
44
}
12304
12305
// Process NavCancel input (to close a popup, get back to parent, clear focus)
12306
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12307
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12308
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
12309
static void ImGui::NavUpdateCancelRequest()
12310
167k
{
12311
167k
    ImGuiContext& g = *GImGui;
12312
167k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12313
167k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12314
167k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
12315
164k
        return;
12316
12317
2.42k
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12318
2.42k
    if (g.ActiveId != 0)
12319
0
    {
12320
0
        ClearActiveID();
12321
0
    }
12322
2.42k
    else if (g.NavLayer != ImGuiNavLayer_Main)
12323
0
    {
12324
        // Leave the "menu" layer
12325
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12326
0
        NavRestoreHighlightAfterMove();
12327
0
    }
12328
2.42k
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
12329
700
    {
12330
        // Exit child window
12331
700
        ImGuiWindow* child_window = g.NavWindow;
12332
700
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
12333
700
        IM_ASSERT(child_window->ChildId != 0);
12334
700
        ImRect child_rect = child_window->Rect();
12335
700
        FocusWindow(parent_window);
12336
700
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
12337
700
        NavRestoreHighlightAfterMove();
12338
700
    }
12339
1.72k
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12340
0
    {
12341
        // Close open popup/menu
12342
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
12343
0
    }
12344
1.72k
    else
12345
1.72k
    {
12346
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12347
1.72k
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12348
473
            g.NavWindow->NavLastIds[0] = 0;
12349
1.72k
        g.NavId = 0;
12350
1.72k
    }
12351
2.42k
}
12352
12353
// Handle PageUp/PageDown/Home/End keys
12354
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12355
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12356
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12357
static float ImGui::NavUpdatePageUpPageDown()
12358
73.9k
{
12359
73.9k
    ImGuiContext& g = *GImGui;
12360
73.9k
    ImGuiWindow* window = g.NavWindow;
12361
73.9k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12362
0
        return 0.0f;
12363
12364
73.9k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
12365
73.9k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
12366
73.9k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12367
73.9k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12368
73.9k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12369
62.0k
        return 0.0f;
12370
12371
11.8k
    if (g.NavLayer != ImGuiNavLayer_Main)
12372
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12373
12374
11.8k
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
12375
340
    {
12376
        // Fallback manual-scroll when window has no navigable item
12377
340
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12378
31
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
12379
309
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12380
41
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
12381
268
        else if (home_pressed)
12382
26
            SetScrollY(window, 0.0f);
12383
242
        else if (end_pressed)
12384
16
            SetScrollY(window, window->ScrollMax.y);
12385
340
    }
12386
11.5k
    else
12387
11.5k
    {
12388
11.5k
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12389
11.5k
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12390
11.5k
        float nav_scoring_rect_offset_y = 0.0f;
12391
11.5k
        if (IsKeyPressed(ImGuiKey_PageUp, true))
12392
1.75k
        {
12393
1.75k
            nav_scoring_rect_offset_y = -page_offset_y;
12394
1.75k
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
12395
1.75k
            g.NavMoveClipDir = ImGuiDir_Up;
12396
1.75k
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12397
1.75k
        }
12398
9.80k
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
12399
258
        {
12400
258
            nav_scoring_rect_offset_y = +page_offset_y;
12401
258
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12402
258
            g.NavMoveClipDir = ImGuiDir_Down;
12403
258
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12404
258
        }
12405
9.54k
        else if (home_pressed)
12406
102
        {
12407
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12408
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12409
            // Preserve current horizontal position if we have any.
12410
102
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12411
102
            if (nav_rect_rel.IsInverted())
12412
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12413
102
            g.NavMoveDir = ImGuiDir_Down;
12414
102
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12415
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12416
102
        }
12417
9.44k
        else if (end_pressed)
12418
356
        {
12419
356
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12420
356
            if (nav_rect_rel.IsInverted())
12421
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12422
356
            g.NavMoveDir = ImGuiDir_Up;
12423
356
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12424
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12425
356
        }
12426
11.5k
        return nav_scoring_rect_offset_y;
12427
11.5k
    }
12428
340
    return 0.0f;
12429
11.8k
}
12430
12431
static void ImGui::NavEndFrame()
12432
167k
{
12433
167k
    ImGuiContext& g = *GImGui;
12434
12435
    // Show CTRL+TAB list window
12436
167k
    if (g.NavWindowingTarget != NULL)
12437
0
        NavUpdateWindowingOverlay();
12438
12439
    // Perform wrap-around in menus
12440
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12441
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12442
167k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12443
0
        NavUpdateCreateWrappingRequest();
12444
167k
}
12445
12446
static void ImGui::NavUpdateCreateWrappingRequest()
12447
0
{
12448
0
    ImGuiContext& g = *GImGui;
12449
0
    ImGuiWindow* window = g.NavWindow;
12450
12451
0
    bool do_forward = false;
12452
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12453
0
    ImGuiDir clip_dir = g.NavMoveDir;
12454
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12455
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12456
0
    {
12457
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12458
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12459
0
        {
12460
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12461
0
            clip_dir = ImGuiDir_Up;
12462
0
        }
12463
0
        do_forward = true;
12464
0
    }
12465
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12466
0
    {
12467
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12468
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12469
0
        {
12470
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12471
0
            clip_dir = ImGuiDir_Down;
12472
0
        }
12473
0
        do_forward = true;
12474
0
    }
12475
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12476
0
    {
12477
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12478
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12479
0
        {
12480
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12481
0
            clip_dir = ImGuiDir_Left;
12482
0
        }
12483
0
        do_forward = true;
12484
0
    }
12485
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12486
0
    {
12487
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12488
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12489
0
        {
12490
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12491
0
            clip_dir = ImGuiDir_Right;
12492
0
        }
12493
0
        do_forward = true;
12494
0
    }
12495
0
    if (!do_forward)
12496
0
        return;
12497
0
    window->NavRectRel[g.NavLayer] = bb_rel;
12498
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12499
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12500
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12501
0
}
12502
12503
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12504
0
{
12505
0
    ImGuiContext& g = *GImGui;
12506
0
    IM_UNUSED(g);
12507
0
    int order = window->FocusOrder;
12508
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12509
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12510
0
    return order;
12511
0
}
12512
12513
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12514
0
{
12515
0
    ImGuiContext& g = *GImGui;
12516
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12517
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12518
0
            return g.WindowsFocusOrder[i];
12519
0
    return NULL;
12520
0
}
12521
12522
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12523
0
{
12524
0
    ImGuiContext& g = *GImGui;
12525
0
    IM_ASSERT(g.NavWindowingTarget);
12526
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12527
0
        return;
12528
12529
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12530
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12531
0
    if (!window_target)
12532
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12533
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
12534
0
    {
12535
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12536
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12537
0
    }
12538
0
    g.NavWindowingToggleLayer = false;
12539
0
}
12540
12541
// Windowing management mode
12542
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12543
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12544
static void ImGui::NavUpdateWindowing()
12545
167k
{
12546
167k
    ImGuiContext& g = *GImGui;
12547
167k
    ImGuiIO& io = g.IO;
12548
12549
167k
    ImGuiWindow* apply_focus_window = NULL;
12550
167k
    bool apply_toggle_layer = false;
12551
12552
167k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12553
167k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
12554
167k
    if (!allow_windowing)
12555
0
        g.NavWindowingTarget = NULL;
12556
12557
    // Fade out
12558
167k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12559
0
    {
12560
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12561
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12562
0
            g.NavWindowingTargetAnim = NULL;
12563
0
    }
12564
12565
    // Start CTRL+Tab or Square+L/R window selection
12566
167k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
12567
167k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12568
167k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12569
167k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12570
167k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12571
167k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12572
167k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12573
167k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12574
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12575
0
        {
12576
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12577
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12578
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12579
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
12580
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
12581
12582
            // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
12583
0
            if (keyboard_next_window || keyboard_prev_window)
12584
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
12585
0
        }
12586
12587
    // Gamepad update
12588
167k
    g.NavWindowingTimer += io.DeltaTime;
12589
167k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
12590
0
    {
12591
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
12592
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
12593
12594
        // Select window to focus
12595
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
12596
0
        if (focus_change_dir != 0)
12597
0
        {
12598
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
12599
0
            g.NavWindowingHighlightAlpha = 1.0f;
12600
0
        }
12601
12602
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
12603
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
12604
0
        {
12605
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
12606
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
12607
0
                apply_toggle_layer = true;
12608
0
            else if (!g.NavWindowingToggleLayer)
12609
0
                apply_focus_window = g.NavWindowingTarget;
12610
0
            g.NavWindowingTarget = NULL;
12611
0
        }
12612
0
    }
12613
12614
    // Keyboard: Focus
12615
167k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
12616
0
    {
12617
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
12618
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
12619
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
12620
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
12621
0
        if (keyboard_next_window || keyboard_prev_window)
12622
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
12623
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
12624
0
            apply_focus_window = g.NavWindowingTarget;
12625
0
    }
12626
12627
    // Keyboard: Press and Release ALT to toggle menu layer
12628
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
12629
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
12630
167k
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
12631
0
    {
12632
0
        g.NavWindowingToggleLayer = true;
12633
0
        g.NavInputSource = ImGuiInputSource_Keyboard;
12634
0
    }
12635
167k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
12636
0
    {
12637
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
12638
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
12639
        // We cancel toggling nav layer if an owner has claimed the key.
12640
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
12641
0
            g.NavWindowingToggleLayer = false;
12642
12643
        // Apply layer toggle on release
12644
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
12645
0
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
12646
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
12647
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
12648
0
                    apply_toggle_layer = true;
12649
0
        if (!IsKeyDown(ImGuiMod_Alt))
12650
0
            g.NavWindowingToggleLayer = false;
12651
0
    }
12652
12653
    // Move window
12654
167k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
12655
0
    {
12656
0
        ImVec2 nav_move_dir;
12657
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
12658
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
12659
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
12660
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12661
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
12662
0
        {
12663
0
            const float NAV_MOVE_SPEED = 800.0f;
12664
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
12665
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
12666
0
            g.NavDisableMouseHover = true;
12667
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaPos);
12668
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
12669
0
            {
12670
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
12671
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
12672
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
12673
0
            }
12674
0
        }
12675
0
    }
12676
12677
    // Apply final focus
12678
167k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
12679
0
    {
12680
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
12681
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
12682
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
12683
0
        ClearActiveID();
12684
0
        NavRestoreHighlightAfterMove();
12685
0
        ClosePopupsOverWindow(apply_focus_window, false);
12686
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
12687
0
        apply_focus_window = g.NavWindow;
12688
0
        if (apply_focus_window->NavLastIds[0] == 0)
12689
0
            NavInitWindow(apply_focus_window, false);
12690
12691
        // If the window has ONLY a menu layer (no main layer), select it directly
12692
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
12693
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
12694
        // the target window as already been previewed once.
12695
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
12696
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
12697
        // won't be valid.
12698
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
12699
0
            g.NavLayer = ImGuiNavLayer_Menu;
12700
12701
        // Request OS level focus
12702
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
12703
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
12704
0
    }
12705
167k
    if (apply_focus_window)
12706
0
        g.NavWindowingTarget = NULL;
12707
12708
    // Apply menu/layer toggle
12709
167k
    if (apply_toggle_layer && g.NavWindow)
12710
0
    {
12711
0
        ClearActiveID();
12712
12713
        // Move to parent menu if necessary
12714
0
        ImGuiWindow* new_nav_window = g.NavWindow;
12715
0
        while (new_nav_window->ParentWindow
12716
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
12717
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
12718
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12719
0
            new_nav_window = new_nav_window->ParentWindow;
12720
0
        if (new_nav_window != g.NavWindow)
12721
0
        {
12722
0
            ImGuiWindow* old_nav_window = g.NavWindow;
12723
0
            FocusWindow(new_nav_window);
12724
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
12725
0
        }
12726
12727
        // Toggle layer
12728
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
12729
0
        if (new_nav_layer != g.NavLayer)
12730
0
        {
12731
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
12732
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
12733
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
12734
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
12735
0
            NavRestoreLayer(new_nav_layer);
12736
0
            NavRestoreHighlightAfterMove();
12737
0
        }
12738
0
    }
12739
167k
}
12740
12741
// Window has already passed the IsWindowNavFocusable()
12742
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
12743
0
{
12744
0
    if (window->Flags & ImGuiWindowFlags_Popup)
12745
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
12746
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
12747
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
12748
0
    if (window->DockNodeAsHost)
12749
0
        return "(Dock node)"; // Not normally shown to user.
12750
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
12751
0
}
12752
12753
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
12754
void ImGui::NavUpdateWindowingOverlay()
12755
0
{
12756
0
    ImGuiContext& g = *GImGui;
12757
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
12758
12759
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
12760
0
        return;
12761
12762
0
    if (g.NavWindowingListWindow == NULL)
12763
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
12764
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
12765
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
12766
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
12767
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
12768
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
12769
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
12770
0
    {
12771
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
12772
0
        IM_ASSERT(window != NULL); // Fix static analyzers
12773
0
        if (!IsWindowNavFocusable(window))
12774
0
            continue;
12775
0
        const char* label = window->Name;
12776
0
        if (label == FindRenderedTextEnd(label))
12777
0
            label = GetFallbackWindowNameForWindowingList(window);
12778
0
        Selectable(label, g.NavWindowingTarget == window);
12779
0
    }
12780
0
    End();
12781
0
    PopStyleVar();
12782
0
}
12783
12784
12785
//-----------------------------------------------------------------------------
12786
// [SECTION] DRAG AND DROP
12787
//-----------------------------------------------------------------------------
12788
12789
bool ImGui::IsDragDropActive()
12790
0
{
12791
0
    ImGuiContext& g = *GImGui;
12792
0
    return g.DragDropActive;
12793
0
}
12794
12795
void ImGui::ClearDragDrop()
12796
6
{
12797
6
    ImGuiContext& g = *GImGui;
12798
6
    g.DragDropActive = false;
12799
6
    g.DragDropPayload.Clear();
12800
6
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
12801
6
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
12802
6
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
12803
6
    g.DragDropAcceptFrameCount = -1;
12804
12805
6
    g.DragDropPayloadBufHeap.clear();
12806
6
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12807
6
}
12808
12809
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
12810
// If the item has an identifier:
12811
// - This assume/require the item to be activated (typically via ButtonBehavior).
12812
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
12813
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
12814
// If the item has no identifier:
12815
// - Currently always assume left mouse button.
12816
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
12817
83
{
12818
83
    ImGuiContext& g = *GImGui;
12819
83
    ImGuiWindow* window = g.CurrentWindow;
12820
12821
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
12822
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
12823
83
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
12824
12825
83
    bool source_drag_active = false;
12826
83
    ImGuiID source_id = 0;
12827
83
    ImGuiID source_parent_id = 0;
12828
83
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
12829
83
    {
12830
83
        source_id = g.LastItemData.ID;
12831
83
        if (source_id != 0)
12832
83
        {
12833
            // Common path: items with ID
12834
83
            if (g.ActiveId != source_id)
12835
0
                return false;
12836
83
            if (g.ActiveIdMouseButton != -1)
12837
0
                mouse_button = g.ActiveIdMouseButton;
12838
83
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12839
0
                return false;
12840
83
            g.ActiveIdAllowOverlap = false;
12841
83
        }
12842
0
        else
12843
0
        {
12844
            // Uncommon path: items without ID
12845
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12846
0
                return false;
12847
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
12848
0
                return false;
12849
12850
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
12851
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
12852
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
12853
0
            {
12854
0
                IM_ASSERT(0);
12855
0
                return false;
12856
0
            }
12857
12858
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
12859
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
12860
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
12861
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
12862
            // Rely on keeping other window->LastItemXXX fields intact.
12863
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
12864
0
            KeepAliveID(source_id);
12865
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id);
12866
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
12867
0
            {
12868
0
                SetActiveID(source_id, window);
12869
0
                FocusWindow(window);
12870
0
            }
12871
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
12872
0
                g.ActiveIdAllowOverlap = is_hovered;
12873
0
        }
12874
83
        if (g.ActiveId != source_id)
12875
0
            return false;
12876
83
        source_parent_id = window->IDStack.back();
12877
83
        source_drag_active = IsMouseDragging(mouse_button);
12878
12879
        // Disable navigation and key inputs while dragging + cancel existing request if any
12880
83
        SetActiveIdUsingAllKeyboardKeys();
12881
83
    }
12882
0
    else
12883
0
    {
12884
0
        window = NULL;
12885
0
        source_id = ImHashStr("#SourceExtern");
12886
0
        source_drag_active = true;
12887
0
    }
12888
12889
83
    if (source_drag_active)
12890
18
    {
12891
18
        if (!g.DragDropActive)
12892
3
        {
12893
3
            IM_ASSERT(source_id != 0);
12894
3
            ClearDragDrop();
12895
3
            ImGuiPayload& payload = g.DragDropPayload;
12896
3
            payload.SourceId = source_id;
12897
3
            payload.SourceParentId = source_parent_id;
12898
3
            g.DragDropActive = true;
12899
3
            g.DragDropSourceFlags = flags;
12900
3
            g.DragDropMouseButton = mouse_button;
12901
3
            if (payload.SourceId == g.ActiveId)
12902
3
                g.ActiveIdNoClearOnFocusLoss = true;
12903
3
        }
12904
18
        g.DragDropSourceFrameCount = g.FrameCount;
12905
18
        g.DragDropWithinSource = true;
12906
12907
18
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12908
0
        {
12909
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
12910
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
12911
0
            bool ret = BeginTooltip();
12912
0
            IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
12913
0
            IM_UNUSED(ret);
12914
12915
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
12916
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(g.CurrentWindow);
12917
0
        }
12918
12919
18
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
12920
18
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
12921
12922
18
        return true;
12923
18
    }
12924
65
    return false;
12925
83
}
12926
12927
void ImGui::EndDragDropSource()
12928
18
{
12929
18
    ImGuiContext& g = *GImGui;
12930
18
    IM_ASSERT(g.DragDropActive);
12931
18
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
12932
12933
18
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12934
0
        EndTooltip();
12935
12936
    // Discard the drag if have not called SetDragDropPayload()
12937
18
    if (g.DragDropPayload.DataFrameCount == -1)
12938
0
        ClearDragDrop();
12939
18
    g.DragDropWithinSource = false;
12940
18
}
12941
12942
// Use 'cond' to choose to submit payload on drag start or every frame
12943
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
12944
18
{
12945
18
    ImGuiContext& g = *GImGui;
12946
18
    ImGuiPayload& payload = g.DragDropPayload;
12947
18
    if (cond == 0)
12948
18
        cond = ImGuiCond_Always;
12949
12950
18
    IM_ASSERT(type != NULL);
12951
18
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
12952
18
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
12953
18
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
12954
18
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
12955
12956
18
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
12957
18
    {
12958
        // Copy payload
12959
18
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
12960
18
        g.DragDropPayloadBufHeap.resize(0);
12961
18
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
12962
0
        {
12963
            // Store in heap
12964
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
12965
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
12966
0
            memcpy(payload.Data, data, data_size);
12967
0
        }
12968
18
        else if (data_size > 0)
12969
18
        {
12970
            // Store locally
12971
18
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12972
18
            payload.Data = g.DragDropPayloadBufLocal;
12973
18
            memcpy(payload.Data, data, data_size);
12974
18
        }
12975
0
        else
12976
0
        {
12977
0
            payload.Data = NULL;
12978
0
        }
12979
18
        payload.DataSize = (int)data_size;
12980
18
    }
12981
18
    payload.DataFrameCount = g.FrameCount;
12982
12983
    // Return whether the payload has been accepted
12984
18
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
12985
18
}
12986
12987
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
12988
27
{
12989
27
    ImGuiContext& g = *GImGui;
12990
27
    if (!g.DragDropActive)
12991
0
        return false;
12992
12993
27
    ImGuiWindow* window = g.CurrentWindow;
12994
27
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
12995
27
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
12996
27
        return false;
12997
0
    IM_ASSERT(id != 0);
12998
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
12999
0
        return false;
13000
0
    if (window->SkipItems)
13001
0
        return false;
13002
13003
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13004
0
    g.DragDropTargetRect = bb;
13005
0
    g.DragDropTargetId = id;
13006
0
    g.DragDropWithinTarget = true;
13007
0
    return true;
13008
0
}
13009
13010
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13011
// 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
13012
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13013
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13014
bool ImGui::BeginDragDropTarget()
13015
0
{
13016
0
    ImGuiContext& g = *GImGui;
13017
0
    if (!g.DragDropActive)
13018
0
        return false;
13019
13020
0
    ImGuiWindow* window = g.CurrentWindow;
13021
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13022
0
        return false;
13023
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13024
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
13025
0
        return false;
13026
13027
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13028
0
    ImGuiID id = g.LastItemData.ID;
13029
0
    if (id == 0)
13030
0
    {
13031
0
        id = window->GetIDFromRectangle(display_rect);
13032
0
        KeepAliveID(id);
13033
0
    }
13034
0
    if (g.DragDropPayload.SourceId == id)
13035
0
        return false;
13036
13037
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13038
0
    g.DragDropTargetRect = display_rect;
13039
0
    g.DragDropTargetId = id;
13040
0
    g.DragDropWithinTarget = true;
13041
0
    return true;
13042
0
}
13043
13044
bool ImGui::IsDragDropPayloadBeingAccepted()
13045
36
{
13046
36
    ImGuiContext& g = *GImGui;
13047
36
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13048
36
}
13049
13050
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13051
0
{
13052
0
    ImGuiContext& g = *GImGui;
13053
0
    ImGuiWindow* window = g.CurrentWindow;
13054
0
    ImGuiPayload& payload = g.DragDropPayload;
13055
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13056
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
13057
0
    if (type != NULL && !payload.IsDataType(type))
13058
0
        return NULL;
13059
13060
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13061
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13062
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13063
0
    ImRect r = g.DragDropTargetRect;
13064
0
    float r_surface = r.GetWidth() * r.GetHeight();
13065
0
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13066
0
        return NULL;
13067
13068
0
    g.DragDropAcceptFlags = flags;
13069
0
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
13070
0
    g.DragDropAcceptIdCurrRectSurface = r_surface;
13071
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13072
13073
    // Render default drop visuals
13074
0
    payload.Preview = was_accepted_previously;
13075
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13076
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13077
0
        window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13078
13079
0
    g.DragDropAcceptFrameCount = g.FrameCount;
13080
0
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
13081
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13082
0
        return NULL;
13083
13084
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
13085
0
    return &payload;
13086
0
}
13087
13088
// FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13089
void ImGui::RenderDragDropTargetRect(const ImRect& bb)
13090
0
{
13091
0
    GetWindowDrawList()->AddRect(bb.Min - ImVec2(3.5f, 3.5f), bb.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13092
0
}
13093
13094
const ImGuiPayload* ImGui::GetDragDropPayload()
13095
0
{
13096
0
    ImGuiContext& g = *GImGui;
13097
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13098
0
}
13099
13100
void ImGui::EndDragDropTarget()
13101
0
{
13102
0
    ImGuiContext& g = *GImGui;
13103
0
    IM_ASSERT(g.DragDropActive);
13104
0
    IM_ASSERT(g.DragDropWithinTarget);
13105
0
    g.DragDropWithinTarget = false;
13106
13107
    // Clear drag and drop state payload right after delivery
13108
0
    if (g.DragDropPayload.Delivery)
13109
0
        ClearDragDrop();
13110
0
}
13111
13112
//-----------------------------------------------------------------------------
13113
// [SECTION] LOGGING/CAPTURING
13114
//-----------------------------------------------------------------------------
13115
// All text output from the interface can be captured into tty/file/clipboard.
13116
// By default, tree nodes are automatically opened during logging.
13117
//-----------------------------------------------------------------------------
13118
13119
// Pass text data straight to log (without being displayed)
13120
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13121
0
{
13122
0
    if (g.LogFile)
13123
0
    {
13124
0
        g.LogBuffer.Buf.resize(0);
13125
0
        g.LogBuffer.appendfv(fmt, args);
13126
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
13127
0
    }
13128
0
    else
13129
0
    {
13130
0
        g.LogBuffer.appendfv(fmt, args);
13131
0
    }
13132
0
}
13133
13134
void ImGui::LogText(const char* fmt, ...)
13135
0
{
13136
0
    ImGuiContext& g = *GImGui;
13137
0
    if (!g.LogEnabled)
13138
0
        return;
13139
13140
0
    va_list args;
13141
0
    va_start(args, fmt);
13142
0
    LogTextV(g, fmt, args);
13143
0
    va_end(args);
13144
0
}
13145
13146
void ImGui::LogTextV(const char* fmt, va_list args)
13147
0
{
13148
0
    ImGuiContext& g = *GImGui;
13149
0
    if (!g.LogEnabled)
13150
0
        return;
13151
13152
0
    LogTextV(g, fmt, args);
13153
0
}
13154
13155
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13156
// We split text into individual lines to add current tree level padding
13157
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13158
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13159
0
{
13160
0
    ImGuiContext& g = *GImGui;
13161
0
    ImGuiWindow* window = g.CurrentWindow;
13162
13163
0
    const char* prefix = g.LogNextPrefix;
13164
0
    const char* suffix = g.LogNextSuffix;
13165
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13166
13167
0
    if (!text_end)
13168
0
        text_end = FindRenderedTextEnd(text, text_end);
13169
13170
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13171
0
    if (ref_pos)
13172
0
        g.LogLinePosY = ref_pos->y;
13173
0
    if (log_new_line)
13174
0
    {
13175
0
        LogText(IM_NEWLINE);
13176
0
        g.LogLineFirstItem = true;
13177
0
    }
13178
13179
0
    if (prefix)
13180
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
13181
13182
    // Re-adjust padding if we have popped out of our starting depth
13183
0
    if (g.LogDepthRef > window->DC.TreeDepth)
13184
0
        g.LogDepthRef = window->DC.TreeDepth;
13185
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13186
13187
0
    const char* text_remaining = text;
13188
0
    for (;;)
13189
0
    {
13190
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13191
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13192
0
        const char* line_start = text_remaining;
13193
0
        const char* line_end = ImStreolRange(line_start, text_end);
13194
0
        const bool is_last_line = (line_end == text_end);
13195
0
        if (line_start != line_end || !is_last_line)
13196
0
        {
13197
0
            const int line_length = (int)(line_end - line_start);
13198
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13199
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
13200
0
            g.LogLineFirstItem = false;
13201
0
            if (*line_end == '\n')
13202
0
            {
13203
0
                LogText(IM_NEWLINE);
13204
0
                g.LogLineFirstItem = true;
13205
0
            }
13206
0
        }
13207
0
        if (is_last_line)
13208
0
            break;
13209
0
        text_remaining = line_end + 1;
13210
0
    }
13211
13212
0
    if (suffix)
13213
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
13214
0
}
13215
13216
// Start logging/capturing text output
13217
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13218
0
{
13219
0
    ImGuiContext& g = *GImGui;
13220
0
    ImGuiWindow* window = g.CurrentWindow;
13221
0
    IM_ASSERT(g.LogEnabled == false);
13222
0
    IM_ASSERT(g.LogFile == NULL);
13223
0
    IM_ASSERT(g.LogBuffer.empty());
13224
0
    g.LogEnabled = true;
13225
0
    g.LogType = type;
13226
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13227
0
    g.LogDepthRef = window->DC.TreeDepth;
13228
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
13229
0
    g.LogLinePosY = FLT_MAX;
13230
0
    g.LogLineFirstItem = true;
13231
0
}
13232
13233
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
13234
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
13235
0
{
13236
0
    ImGuiContext& g = *GImGui;
13237
0
    g.LogNextPrefix = prefix;
13238
0
    g.LogNextSuffix = suffix;
13239
0
}
13240
13241
void ImGui::LogToTTY(int auto_open_depth)
13242
0
{
13243
0
    ImGuiContext& g = *GImGui;
13244
0
    if (g.LogEnabled)
13245
0
        return;
13246
0
    IM_UNUSED(auto_open_depth);
13247
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13248
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
13249
0
    g.LogFile = stdout;
13250
0
#endif
13251
0
}
13252
13253
// Start logging/capturing text output to given file
13254
void ImGui::LogToFile(int auto_open_depth, const char* filename)
13255
0
{
13256
0
    ImGuiContext& g = *GImGui;
13257
0
    if (g.LogEnabled)
13258
0
        return;
13259
13260
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
13261
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
13262
    // By opening the file in binary mode "ab" we have consistent output everywhere.
13263
0
    if (!filename)
13264
0
        filename = g.IO.LogFilename;
13265
0
    if (!filename || !filename[0])
13266
0
        return;
13267
0
    ImFileHandle f = ImFileOpen(filename, "ab");
13268
0
    if (!f)
13269
0
    {
13270
0
        IM_ASSERT(0);
13271
0
        return;
13272
0
    }
13273
13274
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
13275
0
    g.LogFile = f;
13276
0
}
13277
13278
// Start logging/capturing text output to clipboard
13279
void ImGui::LogToClipboard(int auto_open_depth)
13280
0
{
13281
0
    ImGuiContext& g = *GImGui;
13282
0
    if (g.LogEnabled)
13283
0
        return;
13284
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
13285
0
}
13286
13287
void ImGui::LogToBuffer(int auto_open_depth)
13288
0
{
13289
0
    ImGuiContext& g = *GImGui;
13290
0
    if (g.LogEnabled)
13291
0
        return;
13292
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
13293
0
}
13294
13295
void ImGui::LogFinish()
13296
336k
{
13297
336k
    ImGuiContext& g = *GImGui;
13298
336k
    if (!g.LogEnabled)
13299
336k
        return;
13300
13301
0
    LogText(IM_NEWLINE);
13302
0
    switch (g.LogType)
13303
0
    {
13304
0
    case ImGuiLogType_TTY:
13305
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13306
0
        fflush(g.LogFile);
13307
0
#endif
13308
0
        break;
13309
0
    case ImGuiLogType_File:
13310
0
        ImFileClose(g.LogFile);
13311
0
        break;
13312
0
    case ImGuiLogType_Buffer:
13313
0
        break;
13314
0
    case ImGuiLogType_Clipboard:
13315
0
        if (!g.LogBuffer.empty())
13316
0
            SetClipboardText(g.LogBuffer.begin());
13317
0
        break;
13318
0
    case ImGuiLogType_None:
13319
0
        IM_ASSERT(0);
13320
0
        break;
13321
0
    }
13322
13323
0
    g.LogEnabled = false;
13324
0
    g.LogType = ImGuiLogType_None;
13325
0
    g.LogFile = NULL;
13326
0
    g.LogBuffer.clear();
13327
0
}
13328
13329
// Helper to display logging buttons
13330
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13331
void ImGui::LogButtons()
13332
0
{
13333
0
    ImGuiContext& g = *GImGui;
13334
13335
0
    PushID("LogButtons");
13336
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13337
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
13338
#else
13339
    const bool log_to_tty = false;
13340
#endif
13341
0
    const bool log_to_file = Button("Log To File"); SameLine();
13342
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
13343
0
    PushTabStop(false);
13344
0
    SetNextItemWidth(80.0f);
13345
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
13346
0
    PopTabStop();
13347
0
    PopID();
13348
13349
    // Start logging at the end of the function so that the buttons don't appear in the log
13350
0
    if (log_to_tty)
13351
0
        LogToTTY();
13352
0
    if (log_to_file)
13353
0
        LogToFile();
13354
0
    if (log_to_clipboard)
13355
0
        LogToClipboard();
13356
0
}
13357
13358
13359
//-----------------------------------------------------------------------------
13360
// [SECTION] SETTINGS
13361
//-----------------------------------------------------------------------------
13362
// - UpdateSettings() [Internal]
13363
// - MarkIniSettingsDirty() [Internal]
13364
// - FindSettingsHandler() [Internal]
13365
// - ClearIniSettings() [Internal]
13366
// - LoadIniSettingsFromDisk()
13367
// - LoadIniSettingsFromMemory()
13368
// - SaveIniSettingsToDisk()
13369
// - SaveIniSettingsToMemory()
13370
//-----------------------------------------------------------------------------
13371
// - CreateNewWindowSettings() [Internal]
13372
// - FindWindowSettingsByID() [Internal]
13373
// - FindWindowSettingsByWindow() [Internal]
13374
// - ClearWindowSettings() [Internal]
13375
// - WindowSettingsHandler_***() [Internal]
13376
//-----------------------------------------------------------------------------
13377
13378
// Called by NewFrame()
13379
void ImGui::UpdateSettings()
13380
167k
{
13381
    // Load settings on first frame (if not explicitly loaded manually before)
13382
167k
    ImGuiContext& g = *GImGui;
13383
167k
    if (!g.SettingsLoaded)
13384
3
    {
13385
3
        IM_ASSERT(g.SettingsWindows.empty());
13386
3
        if (g.IO.IniFilename)
13387
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
13388
3
        g.SettingsLoaded = true;
13389
3
    }
13390
13391
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
13392
167k
    if (g.SettingsDirtyTimer > 0.0f)
13393
5.10k
    {
13394
5.10k
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
13395
5.10k
        if (g.SettingsDirtyTimer <= 0.0f)
13396
17
        {
13397
17
            if (g.IO.IniFilename != NULL)
13398
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
13399
17
            else
13400
17
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13401
17
            g.SettingsDirtyTimer = 0.0f;
13402
17
        }
13403
5.10k
    }
13404
167k
}
13405
13406
void ImGui::MarkIniSettingsDirty()
13407
0
{
13408
0
    ImGuiContext& g = *GImGui;
13409
0
    if (g.SettingsDirtyTimer <= 0.0f)
13410
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
13411
0
}
13412
13413
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13414
19.7k
{
13415
19.7k
    ImGuiContext& g = *GImGui;
13416
19.7k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13417
273
        if (g.SettingsDirtyTimer <= 0.0f)
13418
17
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13419
19.7k
}
13420
13421
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13422
6
{
13423
6
    ImGuiContext& g = *GImGui;
13424
6
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13425
6
    g.SettingsHandlers.push_back(*handler);
13426
6
}
13427
13428
void ImGui::RemoveSettingsHandler(const char* type_name)
13429
0
{
13430
0
    ImGuiContext& g = *GImGui;
13431
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13432
0
        g.SettingsHandlers.erase(handler);
13433
0
}
13434
13435
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13436
6
{
13437
6
    ImGuiContext& g = *GImGui;
13438
6
    const ImGuiID type_hash = ImHashStr(type_name);
13439
9
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13440
3
        if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
13441
0
            return &g.SettingsHandlers[handler_n];
13442
6
    return NULL;
13443
6
}
13444
13445
// Clear all settings (windows, tables, docking etc.)
13446
void ImGui::ClearIniSettings()
13447
0
{
13448
0
    ImGuiContext& g = *GImGui;
13449
0
    g.SettingsIniData.clear();
13450
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13451
0
        if (g.SettingsHandlers[handler_n].ClearAllFn)
13452
0
            g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
13453
0
}
13454
13455
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13456
0
{
13457
0
    size_t file_data_size = 0;
13458
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13459
0
    if (!file_data)
13460
0
        return;
13461
0
    if (file_data_size > 0)
13462
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13463
0
    IM_FREE(file_data);
13464
0
}
13465
13466
// Zero-tolerance, no error reporting, cheap .ini parsing
13467
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
13468
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13469
0
{
13470
0
    ImGuiContext& g = *GImGui;
13471
0
    IM_ASSERT(g.Initialized);
13472
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13473
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13474
13475
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13476
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13477
0
    if (ini_size == 0)
13478
0
        ini_size = strlen(ini_data);
13479
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13480
0
    char* const buf = g.SettingsIniData.Buf.Data;
13481
0
    char* const buf_end = buf + ini_size;
13482
0
    memcpy(buf, ini_data, ini_size);
13483
0
    buf_end[0] = 0;
13484
13485
    // Call pre-read handlers
13486
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13487
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13488
0
        if (g.SettingsHandlers[handler_n].ReadInitFn)
13489
0
            g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
13490
13491
0
    void* entry_data = NULL;
13492
0
    ImGuiSettingsHandler* entry_handler = NULL;
13493
13494
0
    char* line_end = NULL;
13495
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
13496
0
    {
13497
        // Skip new lines markers, then find end of the line
13498
0
        while (*line == '\n' || *line == '\r')
13499
0
            line++;
13500
0
        line_end = line;
13501
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13502
0
            line_end++;
13503
0
        line_end[0] = 0;
13504
0
        if (line[0] == ';')
13505
0
            continue;
13506
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13507
0
        {
13508
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13509
0
            line_end[-1] = 0;
13510
0
            const char* name_end = line_end - 1;
13511
0
            const char* type_start = line + 1;
13512
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13513
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13514
0
            if (!type_end || !name_start)
13515
0
                continue;
13516
0
            *type_end = 0; // Overwrite first ']'
13517
0
            name_start++;  // Skip second '['
13518
0
            entry_handler = FindSettingsHandler(type_start);
13519
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13520
0
        }
13521
0
        else if (entry_handler != NULL && entry_data != NULL)
13522
0
        {
13523
            // Let type handler parse the line
13524
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13525
0
        }
13526
0
    }
13527
0
    g.SettingsLoaded = true;
13528
13529
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13530
0
    memcpy(buf, ini_data, ini_size);
13531
13532
    // Call post-read handlers
13533
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13534
0
        if (g.SettingsHandlers[handler_n].ApplyAllFn)
13535
0
            g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
13536
0
}
13537
13538
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13539
0
{
13540
0
    ImGuiContext& g = *GImGui;
13541
0
    g.SettingsDirtyTimer = 0.0f;
13542
0
    if (!ini_filename)
13543
0
        return;
13544
13545
0
    size_t ini_data_size = 0;
13546
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13547
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13548
0
    if (!f)
13549
0
        return;
13550
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13551
0
    ImFileClose(f);
13552
0
}
13553
13554
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13555
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13556
0
{
13557
0
    ImGuiContext& g = *GImGui;
13558
0
    g.SettingsDirtyTimer = 0.0f;
13559
0
    g.SettingsIniData.Buf.resize(0);
13560
0
    g.SettingsIniData.Buf.push_back(0);
13561
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13562
0
    {
13563
0
        ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
13564
0
        handler->WriteAllFn(&g, handler, &g.SettingsIniData);
13565
0
    }
13566
0
    if (out_size)
13567
0
        *out_size = (size_t)g.SettingsIniData.size();
13568
0
    return g.SettingsIniData.c_str();
13569
0
}
13570
13571
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
13572
0
{
13573
0
    ImGuiContext& g = *GImGui;
13574
13575
0
#if !IMGUI_DEBUG_INI_SETTINGS
13576
    // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
13577
    // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
13578
0
    if (const char* p = strstr(name, "###"))
13579
0
        name = p;
13580
0
#endif
13581
0
    const size_t name_len = strlen(name);
13582
13583
    // Allocate chunk
13584
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
13585
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
13586
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
13587
0
    settings->ID = ImHashStr(name, name_len);
13588
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
13589
13590
0
    return settings;
13591
0
}
13592
13593
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
13594
// This is called once per window .ini entry + once per newly instantiated window.
13595
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
13596
6
{
13597
6
    ImGuiContext& g = *GImGui;
13598
6
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13599
0
        if (settings->ID == id && !settings->WantDelete)
13600
0
            return settings;
13601
6
    return NULL;
13602
6
}
13603
13604
// This is faster if you are holding on a Window already as we don't need to perform a search.
13605
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
13606
6
{
13607
6
    ImGuiContext& g = *GImGui;
13608
6
    if (window->SettingsOffset != -1)
13609
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
13610
6
    return FindWindowSettingsByID(window->ID);
13611
6
}
13612
13613
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
13614
void ImGui::ClearWindowSettings(const char* name)
13615
0
{
13616
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
13617
0
    ImGuiContext& g = *GImGui;
13618
0
    ImGuiWindow* window = FindWindowByName(name);
13619
0
    if (window != NULL)
13620
0
    {
13621
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
13622
0
        InitOrLoadWindowSettings(window, NULL);
13623
0
        if (window->DockId != 0)
13624
0
            DockContextProcessUndockWindow(&g, window, true);
13625
0
    }
13626
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
13627
0
        settings->WantDelete = true;
13628
0
}
13629
13630
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13631
0
{
13632
0
    ImGuiContext& g = *ctx;
13633
0
    for (int i = 0; i != g.Windows.Size; i++)
13634
0
        g.Windows[i]->SettingsOffset = -1;
13635
0
    g.SettingsWindows.clear();
13636
0
}
13637
13638
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
13639
0
{
13640
0
    ImGuiID id = ImHashStr(name);
13641
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
13642
0
    if (settings)
13643
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
13644
0
    else
13645
0
        settings = ImGui::CreateNewWindowSettings(name);
13646
0
    settings->ID = id;
13647
0
    settings->WantApply = true;
13648
0
    return (void*)settings;
13649
0
}
13650
13651
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
13652
0
{
13653
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
13654
0
    int x, y;
13655
0
    int i;
13656
0
    ImU32 u1;
13657
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
13658
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
13659
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
13660
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
13661
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
13662
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
13663
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
13664
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
13665
0
}
13666
13667
// Apply to existing windows (if any)
13668
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13669
0
{
13670
0
    ImGuiContext& g = *ctx;
13671
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13672
0
        if (settings->WantApply)
13673
0
        {
13674
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
13675
0
                ApplyWindowSettings(window, settings);
13676
0
            settings->WantApply = false;
13677
0
        }
13678
0
}
13679
13680
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
13681
0
{
13682
    // Gather data from windows that were active during this session
13683
    // (if a window wasn't opened in this session we preserve its settings)
13684
0
    ImGuiContext& g = *ctx;
13685
0
    for (int i = 0; i != g.Windows.Size; i++)
13686
0
    {
13687
0
        ImGuiWindow* window = g.Windows[i];
13688
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
13689
0
            continue;
13690
13691
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
13692
0
        if (!settings)
13693
0
        {
13694
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
13695
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
13696
0
        }
13697
0
        IM_ASSERT(settings->ID == window->ID);
13698
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
13699
0
        settings->Size = ImVec2ih(window->SizeFull);
13700
0
        settings->ViewportId = window->ViewportId;
13701
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
13702
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
13703
0
        settings->DockId = window->DockId;
13704
0
        settings->ClassId = window->WindowClass.ClassId;
13705
0
        settings->DockOrder = window->DockOrder;
13706
0
        settings->Collapsed = window->Collapsed;
13707
0
        settings->WantDelete = false;
13708
0
    }
13709
13710
    // Write to text buffer
13711
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
13712
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13713
0
    {
13714
0
        if (settings->WantDelete)
13715
0
            continue;
13716
0
        const char* settings_name = settings->GetName();
13717
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
13718
0
        if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13719
0
        {
13720
0
            buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
13721
0
            buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
13722
0
        }
13723
0
        if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13724
0
            buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
13725
0
        if (settings->Size.x != 0 || settings->Size.y != 0)
13726
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
13727
0
        buf->appendf("Collapsed=%d\n", settings->Collapsed);
13728
0
        if (settings->DockId != 0)
13729
0
        {
13730
            //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
13731
0
            if (settings->DockOrder == -1)
13732
0
                buf->appendf("DockId=0x%08X\n", settings->DockId);
13733
0
            else
13734
0
                buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
13735
0
            if (settings->ClassId != 0)
13736
0
                buf->appendf("ClassId=0x%08X\n", settings->ClassId);
13737
0
        }
13738
0
        buf->append("\n");
13739
0
    }
13740
0
}
13741
13742
13743
//-----------------------------------------------------------------------------
13744
// [SECTION] LOCALIZATION
13745
//-----------------------------------------------------------------------------
13746
13747
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
13748
3
{
13749
3
    ImGuiContext& g = *GImGui;
13750
27
    for (int n = 0; n < count; n++)
13751
24
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
13752
3
}
13753
13754
13755
//-----------------------------------------------------------------------------
13756
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
13757
//-----------------------------------------------------------------------------
13758
// - GetMainViewport()
13759
// - FindViewportByID()
13760
// - FindViewportByPlatformHandle()
13761
// - SetCurrentViewport() [Internal]
13762
// - SetWindowViewport() [Internal]
13763
// - GetWindowAlwaysWantOwnViewport() [Internal]
13764
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
13765
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
13766
// - TranslateWindowsInViewport() [Internal]
13767
// - ScaleWindowsInViewport() [Internal]
13768
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
13769
// - UpdateViewportsNewFrame() [Internal]
13770
// - UpdateViewportsEndFrame() [Internal]
13771
// - AddUpdateViewport() [Internal]
13772
// - WindowSelectViewport() [Internal]
13773
// - WindowSyncOwnedViewport() [Internal]
13774
// - UpdatePlatformWindows()
13775
// - RenderPlatformWindowsDefault()
13776
// - FindPlatformMonitorForPos() [Internal]
13777
// - FindPlatformMonitorForRect() [Internal]
13778
// - UpdateViewportPlatformMonitor() [Internal]
13779
// - DestroyPlatformWindow() [Internal]
13780
// - DestroyPlatformWindows()
13781
//-----------------------------------------------------------------------------
13782
13783
ImGuiViewport* ImGui::GetMainViewport()
13784
440k
{
13785
440k
    ImGuiContext& g = *GImGui;
13786
440k
    return g.Viewports[0];
13787
440k
}
13788
13789
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
13790
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
13791
167k
{
13792
167k
    ImGuiContext& g = *GImGui;
13793
167k
    for (int n = 0; n < g.Viewports.Size; n++)
13794
167k
        if (g.Viewports[n]->ID == id)
13795
167k
            return g.Viewports[n];
13796
0
    return NULL;
13797
167k
}
13798
13799
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
13800
0
{
13801
0
    ImGuiContext& g = *GImGui;
13802
0
    for (int i = 0; i != g.Viewports.Size; i++)
13803
0
        if (g.Viewports[i]->PlatformHandle == platform_handle)
13804
0
            return g.Viewports[i];
13805
0
    return NULL;
13806
0
}
13807
13808
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
13809
880k
{
13810
880k
    ImGuiContext& g = *GImGui;
13811
880k
    (void)current_window;
13812
13813
880k
    if (viewport)
13814
712k
        viewport->LastFrameActive = g.FrameCount;
13815
880k
    if (g.CurrentViewport == viewport)
13816
545k
        return;
13817
334k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
13818
334k
    g.CurrentViewport = viewport;
13819
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
13820
13821
    // Notify platform layer of viewport changes
13822
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
13823
334k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
13824
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
13825
334k
}
13826
13827
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13828
440k
{
13829
    // Abandon viewport
13830
440k
    if (window->ViewportOwned && window->Viewport->Window == window)
13831
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
13832
13833
440k
    window->Viewport = viewport;
13834
440k
    window->ViewportId = viewport->ID;
13835
440k
    window->ViewportOwned = (viewport->Window == window);
13836
440k
}
13837
13838
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
13839
0
{
13840
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
13841
0
    ImGuiContext& g = *GImGui;
13842
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
13843
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
13844
0
            if (!window->DockIsActive)
13845
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
13846
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
13847
0
                        return true;
13848
0
    return false;
13849
0
}
13850
13851
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13852
0
{
13853
0
    ImGuiContext& g = *GImGui;
13854
0
    if (window->Viewport == viewport)
13855
0
        return false;
13856
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
13857
0
        return false;
13858
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
13859
0
        return false;
13860
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
13861
0
        return false;
13862
0
    if (GetWindowAlwaysWantOwnViewport(window))
13863
0
        return false;
13864
13865
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
13866
0
    for (int n = 0; n < g.Windows.Size; n++)
13867
0
    {
13868
0
        ImGuiWindow* window_behind = g.Windows[n];
13869
0
        if (window_behind == window)
13870
0
            break;
13871
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
13872
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
13873
0
                return false;
13874
0
    }
13875
13876
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
13877
0
    ImGuiViewportP* old_viewport = window->Viewport;
13878
0
    if (window->ViewportOwned)
13879
0
        for (int n = 0; n < g.Windows.Size; n++)
13880
0
            if (g.Windows[n]->Viewport == old_viewport)
13881
0
                SetWindowViewport(g.Windows[n], viewport);
13882
0
    SetWindowViewport(window, viewport);
13883
0
    BringWindowToDisplayFront(window);
13884
13885
0
    return true;
13886
0
}
13887
13888
// FIXME: handle 0 to N host viewports
13889
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
13890
0
{
13891
0
    ImGuiContext& g = *GImGui;
13892
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
13893
0
}
13894
13895
// Translate Dear ImGui windows when a Host Viewport has been moved
13896
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13897
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
13898
0
{
13899
0
    ImGuiContext& g = *GImGui;
13900
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
13901
13902
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
13903
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
13904
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
13905
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
13906
    // and so the window will appear to teleport when releasing the mouse.
13907
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
13908
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
13909
0
    ImVec2 delta_pos = new_pos - old_pos;
13910
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT
13911
0
        if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect())))
13912
0
            TranslateWindow(g.Windows[window_n], delta_pos);
13913
0
}
13914
13915
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
13916
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
13917
0
{
13918
0
    ImGuiContext& g = *GImGui;
13919
0
    if (viewport->Window)
13920
0
    {
13921
0
        ScaleWindow(viewport->Window, scale);
13922
0
    }
13923
0
    else
13924
0
    {
13925
0
        for (int i = 0; i != g.Windows.Size; i++)
13926
0
            if (g.Windows[i]->Viewport == viewport)
13927
0
                ScaleWindow(g.Windows[i], scale);
13928
0
    }
13929
0
}
13930
13931
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
13932
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13933
// B) It requires Platform_GetWindowFocus to be implemented by backend.
13934
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
13935
0
{
13936
0
    ImGuiContext& g = *GImGui;
13937
0
    ImGuiViewportP* best_candidate = NULL;
13938
0
    for (int n = 0; n < g.Viewports.Size; n++)
13939
0
    {
13940
0
        ImGuiViewportP* viewport = g.Viewports[n];
13941
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
13942
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
13943
0
                best_candidate = viewport;
13944
0
    }
13945
0
    return best_candidate;
13946
0
}
13947
13948
// Update viewports and monitor infos
13949
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
13950
static void ImGui::UpdateViewportsNewFrame()
13951
167k
{
13952
167k
    ImGuiContext& g = *GImGui;
13953
167k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
13954
13955
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
13956
    // Update Focused status
13957
167k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
13958
167k
    if (viewports_enabled)
13959
0
    {
13960
0
        ImGuiViewportP* focused_viewport = NULL;
13961
0
        for (int n = 0; n < g.Viewports.Size; n++)
13962
0
        {
13963
0
            ImGuiViewportP* viewport = g.Viewports[n];
13964
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
13965
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
13966
0
            {
13967
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
13968
0
                if (is_minimized)
13969
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
13970
0
                else
13971
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
13972
0
            }
13973
13974
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
13975
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
13976
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
13977
0
            {
13978
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
13979
0
                if (is_focused)
13980
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
13981
0
                else
13982
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
13983
0
                if (is_focused)
13984
0
                    focused_viewport = viewport;
13985
0
            }
13986
0
        }
13987
13988
        // Focused viewport has changed?
13989
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
13990
0
        {
13991
            // Store a tag so we can infer z-order easily from all our windows
13992
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
13993
            // will keep the front most stamp instead of losing it back to their parent viewport.
13994
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
13995
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
13996
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
13997
13998
            // Focus associated dear imgui window if focus didn't happen with a click within imgui boundaries (#6299)
13999
            // e.g. Clicking platform title bar.
14000
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
14001
0
            if (!IsAnyMouseDown())
14002
0
            {
14003
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
14004
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
14005
0
                if (focused_viewport->Window != NULL)
14006
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
14007
0
                else if (focused_viewport->LastFocusedHadNavWindow)
14008
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
14009
0
                else
14010
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
14011
0
            }
14012
0
        }
14013
0
        if (focused_viewport)
14014
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
14015
0
    }
14016
14017
    // Create/update main viewport with current platform position.
14018
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14019
167k
    ImGuiViewportP* main_viewport = g.Viewports[0];
14020
167k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
14021
167k
    IM_ASSERT(main_viewport->Window == NULL);
14022
167k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
14023
167k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
14024
167k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
14025
0
    {
14026
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
14027
0
        main_viewport_size = main_viewport->Size;
14028
0
    }
14029
167k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
14030
14031
167k
    g.CurrentDpiScale = 0.0f;
14032
167k
    g.CurrentViewport = NULL;
14033
167k
    g.MouseViewport = NULL;
14034
334k
    for (int n = 0; n < g.Viewports.Size; n++)
14035
167k
    {
14036
167k
        ImGuiViewportP* viewport = g.Viewports[n];
14037
167k
        viewport->Idx = n;
14038
14039
        // Erase unused viewports
14040
167k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
14041
0
        {
14042
0
            DestroyViewport(viewport);
14043
0
            n--;
14044
0
            continue;
14045
0
        }
14046
14047
167k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
14048
167k
        if (viewports_enabled)
14049
0
        {
14050
            // Update Position and Size (from Platform Window to ImGui) if requested.
14051
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
14052
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
14053
0
            {
14054
                // Viewport->WorkPos and WorkSize will be updated below
14055
0
                if (viewport->PlatformRequestMove)
14056
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
14057
0
                if (viewport->PlatformRequestResize)
14058
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
14059
0
            }
14060
0
        }
14061
14062
        // Update/copy monitor info
14063
167k
        UpdateViewportPlatformMonitor(viewport);
14064
14065
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
14066
167k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14067
167k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14068
167k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14069
167k
        viewport->UpdateWorkRect();
14070
14071
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
14072
167k
        viewport->Alpha = 1.0f;
14073
14074
        // Translate Dear ImGui windows when a Host Viewport has been moved
14075
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14076
167k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
14077
167k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
14078
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
14079
14080
        // Update DPI scale
14081
167k
        float new_dpi_scale;
14082
167k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
14083
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
14084
167k
        else if (viewport->PlatformMonitor != -1)
14085
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14086
167k
        else
14087
167k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
14088
167k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
14089
0
        {
14090
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
14091
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
14092
0
                ScaleWindowsInViewport(viewport, scale_factor);
14093
            //if (viewport == GetMainViewport())
14094
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
14095
14096
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
14097
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
14098
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
14099
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
14100
            //    g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
14101
0
        }
14102
167k
        viewport->DpiScale = new_dpi_scale;
14103
167k
    }
14104
14105
    // Update fallback monitor
14106
167k
    if (g.PlatformIO.Monitors.Size == 0)
14107
167k
    {
14108
167k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
14109
167k
        monitor->MainPos = main_viewport->Pos;
14110
167k
        monitor->MainSize = main_viewport->Size;
14111
167k
        monitor->WorkPos = main_viewport->WorkPos;
14112
167k
        monitor->WorkSize = main_viewport->WorkSize;
14113
167k
        monitor->DpiScale = main_viewport->DpiScale;
14114
167k
    }
14115
14116
167k
    if (!viewports_enabled)
14117
167k
    {
14118
167k
        g.MouseViewport = main_viewport;
14119
167k
        return;
14120
167k
    }
14121
14122
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
14123
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
14124
0
    ImGuiViewportP* viewport_hovered = NULL;
14125
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
14126
0
    {
14127
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
14128
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14129
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
14130
0
    }
14131
0
    else
14132
0
    {
14133
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
14134
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14135
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
14136
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
14137
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
14138
0
    }
14139
0
    if (viewport_hovered != NULL)
14140
0
        g.MouseLastHoveredViewport = viewport_hovered;
14141
0
    else if (g.MouseLastHoveredViewport == NULL)
14142
0
        g.MouseLastHoveredViewport = g.Viewports[0];
14143
14144
    // Update mouse reference viewport
14145
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
14146
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
14147
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
14148
0
        g.MouseViewport = g.MovingWindow->Viewport;
14149
0
    else
14150
0
        g.MouseViewport = g.MouseLastHoveredViewport;
14151
14152
    // When dragging something, always refer to the last hovered viewport.
14153
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14154
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
14155
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
14156
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14157
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14158
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14159
0
        viewport_hovered = g.MouseLastHoveredViewport;
14160
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14161
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14162
0
            g.MouseViewport = viewport_hovered;
14163
14164
0
    IM_ASSERT(g.MouseViewport != NULL);
14165
0
}
14166
14167
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14168
static void ImGui::UpdateViewportsEndFrame()
14169
167k
{
14170
167k
    ImGuiContext& g = *GImGui;
14171
167k
    g.PlatformIO.Viewports.resize(0);
14172
334k
    for (int i = 0; i < g.Viewports.Size; i++)
14173
167k
    {
14174
167k
        ImGuiViewportP* viewport = g.Viewports[i];
14175
167k
        viewport->LastPos = viewport->Pos;
14176
167k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14177
0
            if (i > 0) // Always include main viewport in the list
14178
0
                continue;
14179
167k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
14180
0
            continue;
14181
167k
        if (i > 0)
14182
167k
            IM_ASSERT(viewport->Window != NULL);
14183
167k
        g.PlatformIO.Viewports.push_back(viewport);
14184
167k
    }
14185
167k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
14186
167k
}
14187
14188
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
14189
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
14190
167k
{
14191
167k
    ImGuiContext& g = *GImGui;
14192
167k
    IM_ASSERT(id != 0);
14193
14194
167k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
14195
167k
    if (window != NULL)
14196
0
    {
14197
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
14198
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
14199
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
14200
0
            flags |= ImGuiViewportFlags_NoInputs;
14201
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
14202
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14203
0
    }
14204
14205
167k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
14206
167k
    if (viewport)
14207
167k
    {
14208
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
14209
167k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14210
167k
            viewport->Pos = pos;
14211
167k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14212
167k
            viewport->Size = size;
14213
167k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
14214
167k
    }
14215
0
    else
14216
0
    {
14217
        // New viewport
14218
0
        viewport = IM_NEW(ImGuiViewportP)();
14219
0
        viewport->ID = id;
14220
0
        viewport->Idx = g.Viewports.Size;
14221
0
        viewport->Pos = viewport->LastPos = pos;
14222
0
        viewport->Size = size;
14223
0
        viewport->Flags = flags;
14224
0
        UpdateViewportPlatformMonitor(viewport);
14225
0
        g.Viewports.push_back(viewport);
14226
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
14227
14228
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
14229
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
14230
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
14231
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
14232
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
14233
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
14234
14235
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
14236
        // This is so we can select an appropriate font size on the first frame of our window lifetime
14237
0
        if (viewport->PlatformMonitor != -1)
14238
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14239
0
    }
14240
14241
167k
    viewport->Window = window;
14242
167k
    viewport->LastFrameActive = g.FrameCount;
14243
167k
    viewport->UpdateWorkRect();
14244
167k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
14245
14246
167k
    if (window != NULL)
14247
0
        window->ViewportOwned = true;
14248
14249
167k
    return viewport;
14250
167k
}
14251
14252
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
14253
0
{
14254
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
14255
0
    ImGuiContext& g = *GImGui;
14256
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
14257
0
    {
14258
0
        ImGuiWindow* window = g.Windows[window_n];
14259
0
        if (window->Viewport != viewport)
14260
0
            continue;
14261
0
        window->Viewport = NULL;
14262
0
        window->ViewportOwned = false;
14263
0
    }
14264
0
    if (viewport == g.MouseLastHoveredViewport)
14265
0
        g.MouseLastHoveredViewport = NULL;
14266
14267
    // Destroy
14268
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14269
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
14270
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
14271
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
14272
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
14273
0
    IM_DELETE(viewport);
14274
0
}
14275
14276
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
14277
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
14278
440k
{
14279
440k
    ImGuiContext& g = *GImGui;
14280
440k
    ImGuiWindowFlags flags = window->Flags;
14281
440k
    window->ViewportAllowPlatformMonitorExtend = -1;
14282
14283
    // Restore main viewport if multi-viewport is not supported by the backend
14284
440k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
14285
440k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14286
440k
    {
14287
440k
        SetWindowViewport(window, main_viewport);
14288
440k
        return;
14289
440k
    }
14290
0
    window->ViewportOwned = false;
14291
14292
    // Appearing popups reset their viewport so they can inherit again
14293
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
14294
0
    {
14295
0
        window->Viewport = NULL;
14296
0
        window->ViewportId = 0;
14297
0
    }
14298
14299
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
14300
0
    {
14301
        // By default inherit from parent window
14302
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
14303
0
            window->Viewport = window->ParentWindow->Viewport;
14304
14305
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
14306
0
        if (window->Viewport == NULL && window->ViewportId != 0)
14307
0
        {
14308
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
14309
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
14310
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
14311
0
        }
14312
0
    }
14313
14314
0
    bool lock_viewport = false;
14315
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
14316
0
    {
14317
        // Code explicitly request a viewport
14318
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
14319
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
14320
0
        lock_viewport = true;
14321
0
    }
14322
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
14323
0
    {
14324
        // Always inherit viewport from parent window
14325
0
        if (window->DockNode && window->DockNode->HostWindow)
14326
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
14327
0
        window->Viewport = window->ParentWindow->Viewport;
14328
0
    }
14329
0
    else if (window->DockNode && window->DockNode->HostWindow)
14330
0
    {
14331
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
14332
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
14333
0
    }
14334
0
    else if (flags & ImGuiWindowFlags_Tooltip)
14335
0
    {
14336
0
        window->Viewport = g.MouseViewport;
14337
0
    }
14338
0
    else if (GetWindowAlwaysWantOwnViewport(window))
14339
0
    {
14340
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14341
0
    }
14342
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
14343
0
    {
14344
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
14345
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14346
0
    }
14347
0
    else
14348
0
    {
14349
        // Merge into host viewport?
14350
        // We cannot test window->ViewportOwned as it set lower in the function.
14351
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
14352
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
14353
0
        if (try_to_merge_into_host_viewport)
14354
0
            UpdateTryMergeWindowIntoHostViewports(window);
14355
0
    }
14356
14357
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
14358
0
    if (window->Viewport == NULL)
14359
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
14360
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14361
14362
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
14363
0
    if (!lock_viewport)
14364
0
    {
14365
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
14366
0
        {
14367
            // We need to take account of the possibility that mouse may become invalid.
14368
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
14369
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
14370
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
14371
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
14372
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
14373
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
14374
0
            else
14375
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14376
0
        }
14377
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
14378
0
        {
14379
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
14380
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
14381
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
14382
0
            {
14383
                // Steal/transfer ownership
14384
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
14385
0
                window->Viewport->Window = window;
14386
0
                window->Viewport->ID = window->ID;
14387
0
                window->Viewport->LastNameHash = 0;
14388
0
            }
14389
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
14390
0
            {
14391
                // New viewport
14392
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
14393
0
            }
14394
0
        }
14395
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
14396
0
        {
14397
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
14398
            // Child windows are kept contained within their parent.
14399
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14400
0
        }
14401
0
    }
14402
14403
    // Update flags
14404
0
    window->ViewportOwned = (window == window->Viewport->Window);
14405
0
    window->ViewportId = window->Viewport->ID;
14406
14407
    // If the OS window has a title bar, hide our imgui title bar
14408
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
14409
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
14410
0
}
14411
14412
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
14413
0
{
14414
0
    ImGuiContext& g = *GImGui;
14415
14416
0
    bool viewport_rect_changed = false;
14417
14418
    // Synchronize window --> viewport in most situations
14419
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
14420
0
    if (window->Viewport->PlatformRequestMove)
14421
0
    {
14422
0
        window->Pos = window->Viewport->Pos;
14423
0
        MarkIniSettingsDirty(window);
14424
0
    }
14425
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
14426
0
    {
14427
0
        viewport_rect_changed = true;
14428
0
        window->Viewport->Pos = window->Pos;
14429
0
    }
14430
14431
0
    if (window->Viewport->PlatformRequestResize)
14432
0
    {
14433
0
        window->Size = window->SizeFull = window->Viewport->Size;
14434
0
        MarkIniSettingsDirty(window);
14435
0
    }
14436
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
14437
0
    {
14438
0
        viewport_rect_changed = true;
14439
0
        window->Viewport->Size = window->Size;
14440
0
    }
14441
0
    window->Viewport->UpdateWorkRect();
14442
14443
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
14444
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
14445
0
    if (viewport_rect_changed)
14446
0
        UpdateViewportPlatformMonitor(window->Viewport);
14447
14448
    // Update common viewport flags
14449
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
14450
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
14451
0
    ImGuiWindowFlags window_flags = window->Flags;
14452
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
14453
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
14454
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
14455
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
14456
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
14457
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
14458
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
14459
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
14460
14461
    // Not correct to set modal as topmost because:
14462
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
14463
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
14464
    //if (flags & ImGuiWindowFlags_Modal)
14465
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
14466
14467
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
14468
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
14469
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
14470
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
14471
0
    if (is_short_lived_floating_window && !is_modal)
14472
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
14473
14474
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
14475
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
14476
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
14477
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
14478
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
14479
14480
    // We can also tell the backend that clearing the platform window won't be necessary,
14481
    // as our window background is filling the viewport and we have disabled BgAlpha.
14482
    // FIXME: Work on support for per-viewport transparency (#2766)
14483
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
14484
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
14485
14486
0
    window->Viewport->Flags = viewport_flags;
14487
14488
    // Update parent viewport ID
14489
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
14490
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
14491
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
14492
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
14493
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
14494
0
    else
14495
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
14496
0
}
14497
14498
// Called by user at the end of the main loop, after EndFrame()
14499
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14500
void ImGui::UpdatePlatformWindows()
14501
0
{
14502
0
    ImGuiContext& g = *GImGui;
14503
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14504
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14505
0
    g.FrameCountPlatformEnded = g.FrameCount;
14506
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14507
0
        return;
14508
14509
    // Create/resize/destroy platform windows to match each active viewport.
14510
    // Skip the main viewport (index 0), which is always fully handled by the application!
14511
0
    for (int i = 1; i < g.Viewports.Size; i++)
14512
0
    {
14513
0
        ImGuiViewportP* viewport = g.Viewports[i];
14514
14515
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14516
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14517
0
        bool destroy_platform_window = false;
14518
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14519
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14520
0
        if (destroy_platform_window)
14521
0
        {
14522
0
            DestroyPlatformWindow(viewport);
14523
0
            continue;
14524
0
        }
14525
14526
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14527
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14528
0
            continue;
14529
14530
        // Create window
14531
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14532
0
        if (is_new_platform_window)
14533
0
        {
14534
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14535
0
            g.PlatformIO.Platform_CreateWindow(viewport);
14536
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14537
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
14538
0
            viewport->LastNameHash = 0;
14539
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14540
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14541
0
            viewport->PlatformWindowCreated = true;
14542
0
        }
14543
14544
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14545
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
14546
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
14547
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
14548
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
14549
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
14550
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
14551
0
        viewport->LastPlatformPos = viewport->Pos;
14552
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
14553
14554
        // Update title bar (if it changed)
14555
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
14556
0
        {
14557
0
            const char* title_begin = window_for_title->Name;
14558
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
14559
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
14560
0
            if (viewport->LastNameHash != title_hash)
14561
0
            {
14562
0
                char title_end_backup_c = *title_end;
14563
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
14564
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
14565
0
                *title_end = title_end_backup_c;
14566
0
                viewport->LastNameHash = title_hash;
14567
0
            }
14568
0
        }
14569
14570
        // Update alpha (if it changed)
14571
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
14572
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
14573
0
        viewport->LastAlpha = viewport->Alpha;
14574
14575
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
14576
0
        if (g.PlatformIO.Platform_UpdateWindow)
14577
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
14578
14579
0
        if (is_new_platform_window)
14580
0
        {
14581
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
14582
0
            if (g.FrameCount < 3)
14583
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14584
14585
            // Show window
14586
0
            g.PlatformIO.Platform_ShowWindow(viewport);
14587
14588
            // Even without focus, we assume the window becomes front-most.
14589
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
14590
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14591
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14592
0
        }
14593
14594
        // Clear request flags
14595
0
        viewport->ClearRequestFlags();
14596
0
    }
14597
0
}
14598
14599
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
14600
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
14601
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
14602
//
14603
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14604
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14605
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14606
//            MyRenderFunction(platform_io.Viewports[i], my_args);
14607
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14608
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14609
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
14610
//
14611
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
14612
0
{
14613
    // Skip the main viewport (index 0), which is always fully handled by the application!
14614
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14615
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14616
0
    {
14617
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14618
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
14619
0
            continue;
14620
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
14621
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
14622
0
    }
14623
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14624
0
    {
14625
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14626
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
14627
0
            continue;
14628
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
14629
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
14630
0
    }
14631
0
}
14632
14633
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
14634
0
{
14635
0
    ImGuiContext& g = *GImGui;
14636
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
14637
0
    {
14638
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14639
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
14640
0
            return monitor_n;
14641
0
    }
14642
0
    return -1;
14643
0
}
14644
14645
// Search for the monitor with the largest intersection area with the given rectangle
14646
// We generally try to avoid searching loops but the monitor count should be very small here
14647
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
14648
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
14649
167k
{
14650
167k
    ImGuiContext& g = *GImGui;
14651
14652
167k
    const int monitor_count = g.PlatformIO.Monitors.Size;
14653
167k
    if (monitor_count <= 1)
14654
167k
        return monitor_count - 1;
14655
14656
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
14657
    // This is necessary for tooltips which always resize down to zero at first.
14658
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
14659
0
    int best_monitor_n = -1;
14660
0
    float best_monitor_surface = 0.001f;
14661
14662
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
14663
0
    {
14664
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14665
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
14666
0
        if (monitor_rect.Contains(rect))
14667
0
            return monitor_n;
14668
0
        ImRect overlapping_rect = rect;
14669
0
        overlapping_rect.ClipWithFull(monitor_rect);
14670
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
14671
0
        if (overlapping_surface < best_monitor_surface)
14672
0
            continue;
14673
0
        best_monitor_surface = overlapping_surface;
14674
0
        best_monitor_n = monitor_n;
14675
0
    }
14676
0
    return best_monitor_n;
14677
0
}
14678
14679
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
14680
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
14681
167k
{
14682
167k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
14683
167k
}
14684
14685
// Return value is always != NULL, but don't hold on it across frames.
14686
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
14687
0
{
14688
0
    ImGuiContext& g = *GImGui;
14689
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
14690
0
    int monitor_idx = viewport->PlatformMonitor;
14691
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
14692
0
        return &g.PlatformIO.Monitors[monitor_idx];
14693
0
    return &g.FallbackMonitor;
14694
0
}
14695
14696
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
14697
0
{
14698
0
    ImGuiContext& g = *GImGui;
14699
0
    if (viewport->PlatformWindowCreated)
14700
0
    {
14701
0
        if (g.PlatformIO.Renderer_DestroyWindow)
14702
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
14703
0
        if (g.PlatformIO.Platform_DestroyWindow)
14704
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
14705
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
14706
14707
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
14708
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
14709
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
14710
0
            viewport->PlatformWindowCreated = false;
14711
0
    }
14712
0
    else
14713
0
    {
14714
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
14715
0
    }
14716
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
14717
0
    viewport->ClearRequestFlags();
14718
0
}
14719
14720
void ImGui::DestroyPlatformWindows()
14721
0
{
14722
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
14723
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
14724
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
14725
    // code to operator a consistent manner.
14726
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
14727
    // crashing if it doesn't have data stored.
14728
0
    ImGuiContext& g = *GImGui;
14729
0
    for (int i = 0; i < g.Viewports.Size; i++)
14730
0
        DestroyPlatformWindow(g.Viewports[i]);
14731
0
}
14732
14733
14734
//-----------------------------------------------------------------------------
14735
// [SECTION] DOCKING
14736
//-----------------------------------------------------------------------------
14737
// Docking: Internal Types
14738
// Docking: Forward Declarations
14739
// Docking: ImGuiDockContext
14740
// Docking: ImGuiDockContext Docking/Undocking functions
14741
// Docking: ImGuiDockNode
14742
// Docking: ImGuiDockNode Tree manipulation functions
14743
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
14744
// Docking: Builder Functions
14745
// Docking: Begin/End Support Functions (called from Begin/End)
14746
// Docking: Settings
14747
//-----------------------------------------------------------------------------
14748
14749
//-----------------------------------------------------------------------------
14750
// Typical Docking call flow: (root level is generally public API):
14751
//-----------------------------------------------------------------------------
14752
// - NewFrame()                               new dear imgui frame
14753
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
14754
//    | - DockContextProcessUndockWindow()    - process one window undocking request
14755
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
14756
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
14757
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
14758
//    | - DockContextProcessDock()            - process one docking request
14759
//    | - DockNodeUpdate()
14760
//    |   - DockNodeUpdateForRootNode()
14761
//    |     - DockNodeUpdateFlagsAndCollapse()
14762
//    |     - DockNodeFindInfo()
14763
//    |   - destroy unused node or tab bar
14764
//    |   - create dock node host window
14765
//    |      - Begin() etc.
14766
//    |   - DockNodeStartMouseMovingWindow()
14767
//    |   - DockNodeTreeUpdatePosSize()
14768
//    |   - DockNodeTreeUpdateSplitter()
14769
//    |   - draw node background
14770
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
14771
//    |     - DockNodeAddTabBar()
14772
//    |     - DockNodeUpdateWindowMenu()
14773
//    |     - DockNodeCalcTabBarLayout()
14774
//    |     - BeginTabBarEx()
14775
//    |     - TabItemEx() calls
14776
//    |     - EndTabBar()
14777
//    |   - BeginDockableDragDropTarget()
14778
//    |      - DockNodeUpdate()               - recurse into child nodes...
14779
//-----------------------------------------------------------------------------
14780
// - DockSpace()                              user submit a dockspace into a window
14781
//    | Begin(Child)                          - create a child window
14782
//    | DockNodeUpdate()                      - call main dock node update function
14783
//    | End(Child)
14784
//    | ItemSize()
14785
//-----------------------------------------------------------------------------
14786
// - Begin()
14787
//    | BeginDocked()
14788
//    | BeginDockableDragDropSource()
14789
//    | BeginDockableDragDropTarget()
14790
//    | - DockNodePreviewDockRender()
14791
//-----------------------------------------------------------------------------
14792
// - EndFrame()
14793
//    | DockContextEndFrame()
14794
//-----------------------------------------------------------------------------
14795
14796
//-----------------------------------------------------------------------------
14797
// Docking: Internal Types
14798
//-----------------------------------------------------------------------------
14799
// - ImGuiDockRequestType
14800
// - ImGuiDockRequest
14801
// - ImGuiDockPreviewData
14802
// - ImGuiDockNodeSettings
14803
// - ImGuiDockContext
14804
//-----------------------------------------------------------------------------
14805
14806
enum ImGuiDockRequestType
14807
{
14808
    ImGuiDockRequestType_None = 0,
14809
    ImGuiDockRequestType_Dock,
14810
    ImGuiDockRequestType_Undock,
14811
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
14812
};
14813
14814
struct ImGuiDockRequest
14815
{
14816
    ImGuiDockRequestType    Type;
14817
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
14818
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
14819
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
14820
    ImGuiDir                DockSplitDir;
14821
    float                   DockSplitRatio;
14822
    bool                    DockSplitOuter;
14823
    ImGuiWindow*            UndockTargetWindow;
14824
    ImGuiDockNode*          UndockTargetNode;
14825
14826
    ImGuiDockRequest()
14827
0
    {
14828
0
        Type = ImGuiDockRequestType_None;
14829
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
14830
0
        DockTargetNode = UndockTargetNode = NULL;
14831
0
        DockSplitDir = ImGuiDir_None;
14832
0
        DockSplitRatio = 0.5f;
14833
0
        DockSplitOuter = false;
14834
0
    }
14835
};
14836
14837
struct ImGuiDockPreviewData
14838
{
14839
    ImGuiDockNode   FutureNode;
14840
    bool            IsDropAllowed;
14841
    bool            IsCenterAvailable;
14842
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
14843
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
14844
    ImGuiDockNode*  SplitNode;
14845
    ImGuiDir        SplitDir;
14846
    float           SplitRatio;
14847
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
14848
14849
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
14850
};
14851
14852
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
14853
struct ImGuiDockNodeSettings
14854
{
14855
    ImGuiID             ID;
14856
    ImGuiID             ParentNodeId;
14857
    ImGuiID             ParentWindowId;
14858
    ImGuiID             SelectedTabId;
14859
    signed char         SplitAxis;
14860
    char                Depth;
14861
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
14862
    ImVec2ih            Pos;
14863
    ImVec2ih            Size;
14864
    ImVec2ih            SizeRef;
14865
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
14866
};
14867
14868
//-----------------------------------------------------------------------------
14869
// Docking: Forward Declarations
14870
//-----------------------------------------------------------------------------
14871
14872
namespace ImGui
14873
{
14874
    // ImGuiDockContext
14875
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
14876
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
14877
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
14878
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
14879
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
14880
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
14881
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
14882
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
14883
14884
    // ImGuiDockNode
14885
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
14886
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14887
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14888
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
14889
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
14890
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
14891
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
14892
    static void             DockNodeUpdate(ImGuiDockNode* node);
14893
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
14894
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
14895
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
14896
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
14897
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
14898
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
14899
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
14900
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
14901
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
14902
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
14903
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
14904
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
14905
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
14906
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
14907
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
14908
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
14909
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
14910
14911
    // ImGuiDockNode tree manipulations
14912
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
14913
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
14914
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
14915
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
14916
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
14917
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
14918
14919
    // Settings
14920
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
14921
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
14922
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
14923
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
14924
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
14925
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
14926
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
14927
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
14928
}
14929
14930
//-----------------------------------------------------------------------------
14931
// Docking: ImGuiDockContext
14932
//-----------------------------------------------------------------------------
14933
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
14934
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
14935
// At boot time only, we run a simple GC to remove nodes that have no references.
14936
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
14937
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
14938
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
14939
//-----------------------------------------------------------------------------
14940
// - DockContextInitialize()
14941
// - DockContextShutdown()
14942
// - DockContextClearNodes()
14943
// - DockContextRebuildNodes()
14944
// - DockContextNewFrameUpdateUndocking()
14945
// - DockContextNewFrameUpdateDocking()
14946
// - DockContextEndFrame()
14947
// - DockContextFindNodeByID()
14948
// - DockContextBindNodeToWindow()
14949
// - DockContextGenNodeID()
14950
// - DockContextAddNode()
14951
// - DockContextRemoveNode()
14952
// - ImGuiDockContextPruneNodeData
14953
// - DockContextPruneUnusedSettingsNodes()
14954
// - DockContextBuildNodesFromSettings()
14955
// - DockContextBuildAddWindowsToNodes()
14956
//-----------------------------------------------------------------------------
14957
14958
void ImGui::DockContextInitialize(ImGuiContext* ctx)
14959
3
{
14960
3
    ImGuiContext& g = *ctx;
14961
14962
    // Add .ini handle for persistent docking data
14963
3
    ImGuiSettingsHandler ini_handler;
14964
3
    ini_handler.TypeName = "Docking";
14965
3
    ini_handler.TypeHash = ImHashStr("Docking");
14966
3
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
14967
3
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
14968
3
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
14969
3
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
14970
3
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
14971
3
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
14972
3
    g.SettingsHandlers.push_back(ini_handler);
14973
14974
3
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
14975
3
}
14976
14977
void ImGui::DockContextShutdown(ImGuiContext* ctx)
14978
0
{
14979
0
    ImGuiDockContext* dc  = &ctx->DockContext;
14980
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14981
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14982
0
            IM_DELETE(node);
14983
0
}
14984
14985
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
14986
0
{
14987
0
    IM_UNUSED(ctx);
14988
0
    IM_ASSERT(ctx == GImGui);
14989
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
14990
0
    DockBuilderRemoveNodeChildNodes(root_id);
14991
0
}
14992
14993
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
14994
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
14995
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
14996
0
{
14997
0
    ImGuiContext& g = *ctx;
14998
0
    ImGuiDockContext* dc = &ctx->DockContext;
14999
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
15000
0
    SaveIniSettingsToMemory();
15001
0
    ImGuiID root_id = 0; // Rebuild all
15002
0
    DockContextClearNodes(ctx, root_id, false);
15003
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
15004
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
15005
0
}
15006
15007
// Docking context update function, called by NewFrame()
15008
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
15009
167k
{
15010
167k
    ImGuiContext& g = *ctx;
15011
167k
    ImGuiDockContext* dc = &ctx->DockContext;
15012
167k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15013
0
    {
15014
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
15015
0
            DockContextClearNodes(ctx, 0, true);
15016
0
        return;
15017
0
    }
15018
15019
    // Setting NoSplit at runtime merges all nodes
15020
167k
    if (g.IO.ConfigDockingNoSplit)
15021
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
15022
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15023
0
                if (node->IsRootNode() && node->IsSplitNode())
15024
0
                {
15025
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
15026
                    //dc->WantFullRebuild = true;
15027
0
                }
15028
15029
    // Process full rebuild
15030
#if 0
15031
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
15032
        dc->WantFullRebuild = true;
15033
#endif
15034
167k
    if (dc->WantFullRebuild)
15035
0
    {
15036
0
        DockContextRebuildNodes(ctx);
15037
0
        dc->WantFullRebuild = false;
15038
0
    }
15039
15040
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
15041
167k
    for (int n = 0; n < dc->Requests.Size; n++)
15042
0
    {
15043
0
        ImGuiDockRequest* req = &dc->Requests[n];
15044
0
        if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
15045
0
            DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
15046
0
        else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
15047
0
            DockContextProcessUndockNode(ctx, req->UndockTargetNode);
15048
0
    }
15049
167k
}
15050
15051
// Docking context update function, called by NewFrame()
15052
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
15053
167k
{
15054
167k
    ImGuiContext& g = *ctx;
15055
167k
    ImGuiDockContext* dc  = &ctx->DockContext;
15056
167k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15057
0
        return;
15058
15059
    // [DEBUG] Store hovered dock node.
15060
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
15061
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
15062
167k
    g.DebugHoveredDockNode = NULL;
15063
167k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
15064
25.3k
    {
15065
25.3k
        if (hovered_window->DockNodeAsHost)
15066
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
15067
25.3k
        else if (hovered_window->RootWindow->DockNode)
15068
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
15069
25.3k
    }
15070
15071
    // Process Docking requests
15072
167k
    for (int n = 0; n < dc->Requests.Size; n++)
15073
0
        if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
15074
0
            DockContextProcessDock(ctx, &dc->Requests[n]);
15075
167k
    dc->Requests.resize(0);
15076
15077
    // Create windows for each automatic docking nodes
15078
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
15079
167k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15080
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15081
0
            if (node->IsFloatingNode())
15082
0
                DockNodeUpdate(node);
15083
167k
}
15084
15085
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
15086
167k
{
15087
    // Draw backgrounds of node missing their window
15088
167k
    ImGuiContext& g = *ctx;
15089
167k
    ImGuiDockContext* dc = &g.DockContext;
15090
167k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15091
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15092
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
15093
0
            {
15094
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
15095
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), DOCKING_SPLITTER_SIZE);
15096
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15097
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
15098
0
            }
15099
167k
}
15100
15101
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
15102
0
{
15103
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
15104
0
}
15105
15106
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
15107
0
{
15108
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
15109
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
15110
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
15111
0
    ImGuiID id = 0x0001;
15112
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
15113
0
        id++;
15114
0
    return id;
15115
0
}
15116
15117
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
15118
0
{
15119
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
15120
0
    ImGuiContext& g = *ctx;
15121
0
    if (id == 0)
15122
0
        id = DockContextGenNodeID(ctx);
15123
0
    else
15124
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
15125
15126
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15127
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15128
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15129
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
15130
0
    return node;
15131
0
}
15132
15133
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15134
0
{
15135
0
    ImGuiContext& g = *ctx;
15136
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15137
15138
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15139
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15140
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15141
0
    IM_ASSERT(node->Windows.Size == 0);
15142
15143
0
    if (node->HostWindow)
15144
0
        node->HostWindow->DockNodeAsHost = NULL;
15145
15146
0
    ImGuiDockNode* parent_node = node->ParentNode;
15147
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15148
0
    if (merge)
15149
0
    {
15150
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15151
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15152
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
15153
0
    }
15154
0
    else
15155
0
    {
15156
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15157
0
            if (parent_node->ChildNodes[n] == node)
15158
0
                node->ParentNode->ChildNodes[n] = NULL;
15159
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
15160
0
        IM_DELETE(node);
15161
0
    }
15162
0
}
15163
15164
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15165
0
{
15166
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15167
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15168
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
15169
0
}
15170
15171
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15172
struct ImGuiDockContextPruneNodeData
15173
{
15174
    int         CountWindows, CountChildWindows, CountChildNodes;
15175
    ImGuiID     RootId;
15176
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
15177
};
15178
15179
// Garbage collect unused nodes (run once at init time)
15180
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
15181
0
{
15182
0
    ImGuiContext& g = *ctx;
15183
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15184
0
    IM_ASSERT(g.Windows.Size == 0);
15185
15186
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
15187
0
    pool.Reserve(dc->NodesSettings.Size);
15188
15189
    // Count child nodes and compute RootID
15190
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15191
0
    {
15192
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15193
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
15194
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
15195
0
        if (settings->ParentNodeId)
15196
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
15197
0
    }
15198
15199
    // Count reference to dock ids from dockspaces
15200
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
15201
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15202
0
    {
15203
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15204
0
        if (settings->ParentWindowId != 0)
15205
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
15206
0
                if (window_settings->DockId)
15207
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
15208
0
                        data->CountChildNodes++;
15209
0
    }
15210
15211
    // Count reference to dock ids from window settings
15212
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
15213
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15214
0
        if (ImGuiID dock_id = settings->DockId)
15215
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
15216
0
            {
15217
0
                data->CountWindows++;
15218
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
15219
0
                    data_root->CountChildWindows++;
15220
0
            }
15221
15222
    // Prune
15223
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15224
0
    {
15225
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15226
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
15227
0
        if (data->CountWindows > 1)
15228
0
            continue;
15229
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
15230
15231
0
        bool remove = false;
15232
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
15233
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
15234
0
        remove |= (data_root->CountChildWindows == 0);
15235
0
        if (remove)
15236
0
        {
15237
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
15238
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
15239
0
            settings->ID = 0;
15240
0
        }
15241
0
    }
15242
0
}
15243
15244
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
15245
0
{
15246
    // Build nodes
15247
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
15248
0
    {
15249
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
15250
0
        if (settings->ID == 0)
15251
0
            continue;
15252
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
15253
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
15254
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
15255
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
15256
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
15257
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
15258
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
15259
0
            node->ParentNode->ChildNodes[0] = node;
15260
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
15261
0
            node->ParentNode->ChildNodes[1] = node;
15262
0
        node->SelectedTabId = settings->SelectedTabId;
15263
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
15264
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
15265
15266
        // Bind host window immediately if it already exist (in case of a rebuild)
15267
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
15268
0
        char host_window_title[20];
15269
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
15270
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
15271
0
    }
15272
0
}
15273
15274
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
15275
0
{
15276
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
15277
0
    ImGuiContext& g = *ctx;
15278
0
    for (int n = 0; n < g.Windows.Size; n++)
15279
0
    {
15280
0
        ImGuiWindow* window = g.Windows[n];
15281
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
15282
0
            continue;
15283
0
        if (window->DockNode != NULL)
15284
0
            continue;
15285
15286
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
15287
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
15288
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
15289
0
            DockNodeAddWindow(node, window, true);
15290
0
    }
15291
0
}
15292
15293
//-----------------------------------------------------------------------------
15294
// Docking: ImGuiDockContext Docking/Undocking functions
15295
//-----------------------------------------------------------------------------
15296
// - DockContextQueueDock()
15297
// - DockContextQueueUndockWindow()
15298
// - DockContextQueueUndockNode()
15299
// - DockContextQueueNotifyRemovedNode()
15300
// - DockContextProcessDock()
15301
// - DockContextProcessUndockWindow()
15302
// - DockContextProcessUndockNode()
15303
// - DockContextCalcDropPosForDocking()
15304
//-----------------------------------------------------------------------------
15305
15306
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
15307
0
{
15308
0
    IM_ASSERT(target != payload);
15309
0
    ImGuiDockRequest req;
15310
0
    req.Type = ImGuiDockRequestType_Dock;
15311
0
    req.DockTargetWindow = target;
15312
0
    req.DockTargetNode = target_node;
15313
0
    req.DockPayload = payload;
15314
0
    req.DockSplitDir = split_dir;
15315
0
    req.DockSplitRatio = split_ratio;
15316
0
    req.DockSplitOuter = split_outer;
15317
0
    ctx->DockContext.Requests.push_back(req);
15318
0
}
15319
15320
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
15321
0
{
15322
0
    ImGuiDockRequest req;
15323
0
    req.Type = ImGuiDockRequestType_Undock;
15324
0
    req.UndockTargetWindow = window;
15325
0
    ctx->DockContext.Requests.push_back(req);
15326
0
}
15327
15328
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15329
0
{
15330
0
    ImGuiDockRequest req;
15331
0
    req.Type = ImGuiDockRequestType_Undock;
15332
0
    req.UndockTargetNode = node;
15333
0
    ctx->DockContext.Requests.push_back(req);
15334
0
}
15335
15336
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
15337
0
{
15338
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15339
0
    for (int n = 0; n < dc->Requests.Size; n++)
15340
0
        if (dc->Requests[n].DockTargetNode == node)
15341
0
            dc->Requests[n].Type = ImGuiDockRequestType_None;
15342
0
}
15343
15344
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
15345
0
{
15346
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
15347
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
15348
15349
0
    ImGuiContext& g = *ctx;
15350
0
    IM_UNUSED(g);
15351
15352
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
15353
0
    ImGuiWindow* target_window = req->DockTargetWindow;
15354
0
    ImGuiDockNode* node = req->DockTargetNode;
15355
0
    if (payload_window)
15356
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
15357
0
    else
15358
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
15359
15360
    // Decide which Tab will be selected at the end of the operation
15361
0
    ImGuiID next_selected_id = 0;
15362
0
    ImGuiDockNode* payload_node = NULL;
15363
0
    if (payload_window)
15364
0
    {
15365
0
        payload_node = payload_window->DockNodeAsHost;
15366
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
15367
0
        if (payload_node && payload_node->IsLeafNode())
15368
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
15369
0
        if (payload_node == NULL)
15370
0
            next_selected_id = payload_window->TabId;
15371
0
    }
15372
15373
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
15374
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
15375
0
    if (node)
15376
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
15377
0
    if (node && target_window && node == target_window->DockNodeAsHost)
15378
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
15379
15380
    // Create new node and add existing window to it
15381
0
    if (node == NULL)
15382
0
    {
15383
0
        node = DockContextAddNode(ctx, 0);
15384
0
        node->Pos = target_window->Pos;
15385
0
        node->Size = target_window->Size;
15386
0
        if (target_window->DockNodeAsHost == NULL)
15387
0
        {
15388
0
            DockNodeAddWindow(node, target_window, true);
15389
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
15390
0
            target_window->DockIsActive = true;
15391
0
        }
15392
0
    }
15393
15394
0
    ImGuiDir split_dir = req->DockSplitDir;
15395
0
    if (split_dir != ImGuiDir_None)
15396
0
    {
15397
        // Split into two, one side will be our payload node unless we are dropping a loose window
15398
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
15399
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
15400
0
        const float split_ratio = req->DockSplitRatio;
15401
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
15402
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
15403
0
        new_node->HostWindow = node->HostWindow;
15404
0
        node = new_node;
15405
0
    }
15406
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15407
15408
0
    if (node != payload_node)
15409
0
    {
15410
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
15411
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
15412
0
        {
15413
0
            DockNodeAddTabBar(node);
15414
0
            for (int n = 0; n < node->Windows.Size; n++)
15415
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15416
0
        }
15417
15418
0
        if (payload_node != NULL)
15419
0
        {
15420
            // Transfer full payload node (with 1+ child windows or child nodes)
15421
0
            if (payload_node->IsSplitNode())
15422
0
            {
15423
0
                if (node->Windows.Size > 0)
15424
0
                {
15425
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
15426
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
15427
                    // This allows us to preserve some of the underlying dock tree settings nicely.
15428
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
15429
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
15430
0
                    if (visible_node->TabBar)
15431
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
15432
0
                    DockNodeMoveWindows(node, visible_node);
15433
0
                    DockNodeMoveWindows(visible_node, node);
15434
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
15435
0
                }
15436
0
                if (node->IsCentralNode())
15437
0
                {
15438
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
15439
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
15440
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
15441
0
                    IM_ASSERT(last_focused_node != NULL);
15442
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
15443
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
15444
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
15445
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
15446
0
                    last_focused_root_node->CentralNode = last_focused_node;
15447
0
                }
15448
15449
0
                IM_ASSERT(node->Windows.Size == 0);
15450
0
                DockNodeMoveChildNodes(node, payload_node);
15451
0
            }
15452
0
            else
15453
0
            {
15454
0
                const ImGuiID payload_dock_id = payload_node->ID;
15455
0
                DockNodeMoveWindows(node, payload_node);
15456
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15457
0
            }
15458
0
            DockContextRemoveNode(ctx, payload_node, true);
15459
0
        }
15460
0
        else if (payload_window)
15461
0
        {
15462
            // Transfer single window
15463
0
            const ImGuiID payload_dock_id = payload_window->DockId;
15464
0
            node->VisibleWindow = payload_window;
15465
0
            DockNodeAddWindow(node, payload_window, true);
15466
0
            if (payload_dock_id != 0)
15467
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15468
0
        }
15469
0
    }
15470
0
    else
15471
0
    {
15472
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
15473
0
        node->WantHiddenTabBarUpdate = true;
15474
0
    }
15475
15476
    // Update selection immediately
15477
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
15478
0
        tab_bar->NextSelectedTabId = next_selected_id;
15479
0
    MarkIniSettingsDirty();
15480
0
}
15481
15482
// Problem:
15483
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15484
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15485
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15486
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15487
// Solution:
15488
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15489
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15490
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15491
0
{
15492
0
    if (ref_viewport == NULL)
15493
0
        return size;
15494
15495
0
    ImGuiContext& g = *GImGui;
15496
0
    ImVec2 max_size = ImFloor(ref_viewport->WorkSize * 0.90f);
15497
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15498
0
    {
15499
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15500
0
        max_size = ImFloor(monitor->WorkSize * 0.90f);
15501
0
    }
15502
0
    return ImMin(size, max_size);
15503
0
}
15504
15505
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15506
0
{
15507
0
    ImGuiContext& g = *ctx;
15508
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15509
0
    if (window->DockNode)
15510
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15511
0
    else
15512
0
        window->DockId = 0;
15513
0
    window->Collapsed = false;
15514
0
    window->DockIsActive = false;
15515
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15516
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15517
15518
0
    MarkIniSettingsDirty();
15519
0
}
15520
15521
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15522
0
{
15523
0
    ImGuiContext& g = *ctx;
15524
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15525
0
    IM_ASSERT(node->IsLeafNode());
15526
0
    IM_ASSERT(node->Windows.Size >= 1);
15527
15528
0
    if (node->IsRootNode() || node->IsCentralNode())
15529
0
    {
15530
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15531
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15532
0
        new_node->Pos = node->Pos;
15533
0
        new_node->Size = node->Size;
15534
0
        new_node->SizeRef = node->SizeRef;
15535
0
        DockNodeMoveWindows(new_node, node);
15536
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15537
0
        node = new_node;
15538
0
    }
15539
0
    else
15540
0
    {
15541
        // Otherwise extract our node and merge our sibling back into the parent node.
15542
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15543
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15544
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15545
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15546
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
15547
0
        node->ParentNode = NULL;
15548
0
    }
15549
0
    for (int n = 0; n < node->Windows.Size; n++)
15550
0
    {
15551
0
        ImGuiWindow* window = node->Windows[n];
15552
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15553
0
        if (window->ParentWindow)
15554
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
15555
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
15556
0
    }
15557
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
15558
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
15559
0
    node->WantMouseMove = true;
15560
0
    MarkIniSettingsDirty();
15561
0
}
15562
15563
// This is mostly used for automation.
15564
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
15565
0
{
15566
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
15567
    // (which would be functionally identical) we only show the outer one. Reflect this here.
15568
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
15569
0
        split_outer = true;
15570
0
    ImGuiDockPreviewData split_data;
15571
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
15572
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
15573
0
        return false;
15574
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
15575
0
    return true;
15576
0
}
15577
15578
//-----------------------------------------------------------------------------
15579
// Docking: ImGuiDockNode
15580
//-----------------------------------------------------------------------------
15581
// - DockNodeGetTabOrder()
15582
// - DockNodeAddWindow()
15583
// - DockNodeRemoveWindow()
15584
// - DockNodeMoveChildNodes()
15585
// - DockNodeMoveWindows()
15586
// - DockNodeApplyPosSizeToWindows()
15587
// - DockNodeHideHostWindow()
15588
// - ImGuiDockNodeFindInfoResults
15589
// - DockNodeFindInfo()
15590
// - DockNodeFindWindowByID()
15591
// - DockNodeUpdateFlagsAndCollapse()
15592
// - DockNodeUpdateHasCentralNodeFlag()
15593
// - DockNodeUpdateVisibleFlag()
15594
// - DockNodeStartMouseMovingWindow()
15595
// - DockNodeUpdate()
15596
// - DockNodeUpdateWindowMenu()
15597
// - DockNodeBeginAmendTabBar()
15598
// - DockNodeEndAmendTabBar()
15599
// - DockNodeUpdateTabBar()
15600
// - DockNodeAddTabBar()
15601
// - DockNodeRemoveTabBar()
15602
// - DockNodeIsDropAllowedOne()
15603
// - DockNodeIsDropAllowed()
15604
// - DockNodeCalcTabBarLayout()
15605
// - DockNodeCalcSplitRects()
15606
// - DockNodeCalcDropRectsAndTestMousePos()
15607
// - DockNodePreviewDockSetup()
15608
// - DockNodePreviewDockRender()
15609
//-----------------------------------------------------------------------------
15610
15611
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
15612
0
{
15613
0
    ID = id;
15614
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
15615
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
15616
0
    TabBar = NULL;
15617
0
    SplitAxis = ImGuiAxis_None;
15618
15619
0
    State = ImGuiDockNodeState_Unknown;
15620
0
    LastBgColor = IM_COL32_WHITE;
15621
0
    HostWindow = VisibleWindow = NULL;
15622
0
    CentralNode = OnlyNodeWithWindows = NULL;
15623
0
    CountNodeWithWindows = 0;
15624
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
15625
0
    LastFocusedNodeId = 0;
15626
0
    SelectedTabId = 0;
15627
0
    WantCloseTabId = 0;
15628
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
15629
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
15630
0
    IsVisible = true;
15631
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
15632
0
    IsBgDrawnThisFrame = false;
15633
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
15634
0
}
15635
15636
ImGuiDockNode::~ImGuiDockNode()
15637
0
{
15638
0
    IM_DELETE(TabBar);
15639
0
    TabBar = NULL;
15640
0
    ChildNodes[0] = ChildNodes[1] = NULL;
15641
0
}
15642
15643
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
15644
0
{
15645
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
15646
0
    if (tab_bar == NULL)
15647
0
        return -1;
15648
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
15649
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
15650
0
}
15651
15652
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
15653
0
{
15654
0
    window->Hidden = true;
15655
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
15656
0
}
15657
15658
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
15659
0
{
15660
0
    ImGuiContext& g = *GImGui; (void)g;
15661
0
    if (window->DockNode)
15662
0
    {
15663
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
15664
0
        IM_ASSERT(window->DockNode->ID != node->ID);
15665
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
15666
0
    }
15667
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
15668
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15669
15670
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
15671
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
15672
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
15673
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
15674
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
15675
15676
0
    node->Windows.push_back(window);
15677
0
    node->WantHiddenTabBarUpdate = true;
15678
0
    window->DockNode = node;
15679
0
    window->DockId = node->ID;
15680
0
    window->DockIsActive = (node->Windows.Size > 1);
15681
0
    window->DockTabWantClose = false;
15682
15683
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
15684
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
15685
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
15686
0
    {
15687
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
15688
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
15689
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
15690
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
15691
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
15692
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
15693
0
    }
15694
15695
    // Add to tab bar if requested
15696
0
    if (add_to_tab_bar)
15697
0
    {
15698
0
        if (node->TabBar == NULL)
15699
0
        {
15700
0
            DockNodeAddTabBar(node);
15701
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
15702
15703
            // Add existing windows
15704
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
15705
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15706
0
        }
15707
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
15708
0
    }
15709
15710
0
    DockNodeUpdateVisibleFlag(node);
15711
15712
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
15713
0
    if (node->HostWindow)
15714
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
15715
0
}
15716
15717
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
15718
0
{
15719
0
    ImGuiContext& g = *GImGui;
15720
0
    IM_ASSERT(window->DockNode == node);
15721
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
15722
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
15723
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
15724
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15725
15726
0
    window->DockNode = NULL;
15727
0
    window->DockIsActive = window->DockTabWantClose = false;
15728
0
    window->DockId = save_dock_id;
15729
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15730
0
    if (window->ParentWindow)
15731
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
15732
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
15733
15734
    // Remove window
15735
0
    bool erased = false;
15736
0
    for (int n = 0; n < node->Windows.Size; n++)
15737
0
        if (node->Windows[n] == window)
15738
0
        {
15739
0
            node->Windows.erase(node->Windows.Data + n);
15740
0
            erased = true;
15741
0
            break;
15742
0
        }
15743
0
    if (!erased)
15744
0
        IM_ASSERT(erased);
15745
0
    if (node->VisibleWindow == window)
15746
0
        node->VisibleWindow = NULL;
15747
15748
    // Remove tab and possibly tab bar
15749
0
    node->WantHiddenTabBarUpdate = true;
15750
0
    if (node->TabBar)
15751
0
    {
15752
0
        TabBarRemoveTab(node->TabBar, window->TabId);
15753
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
15754
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
15755
0
            DockNodeRemoveTabBar(node);
15756
0
    }
15757
15758
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
15759
0
    {
15760
        // Automatic dock node delete themselves if they are not holding at least one tab
15761
0
        DockContextRemoveNode(&g, node, true);
15762
0
        return;
15763
0
    }
15764
15765
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
15766
0
    {
15767
0
        ImGuiWindow* remaining_window = node->Windows[0];
15768
0
        if (node->HostWindow->ViewportOwned && node->IsRootNode())
15769
0
        {
15770
            // Transfer viewport back to the remaining loose window
15771
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X=>%08X for Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, remaining_window->ID, remaining_window->Name);
15772
0
            IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow);
15773
0
            node->HostWindow->Viewport->Window = remaining_window;
15774
0
            node->HostWindow->Viewport->ID = remaining_window->ID;
15775
0
        }
15776
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
15777
0
    }
15778
15779
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
15780
0
    DockNodeUpdateVisibleFlag(node);
15781
0
}
15782
15783
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15784
0
{
15785
0
    IM_ASSERT(dst_node->Windows.Size == 0);
15786
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
15787
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
15788
0
    if (dst_node->ChildNodes[0])
15789
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
15790
0
    if (dst_node->ChildNodes[1])
15791
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
15792
0
    dst_node->SplitAxis = src_node->SplitAxis;
15793
0
    dst_node->SizeRef = src_node->SizeRef;
15794
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
15795
0
}
15796
15797
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15798
0
{
15799
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
15800
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
15801
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
15802
0
    if (src_tab_bar != NULL)
15803
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
15804
15805
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
15806
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
15807
0
    if (move_tab_bar)
15808
0
    {
15809
0
        dst_node->TabBar = src_node->TabBar;
15810
0
        src_node->TabBar = NULL;
15811
0
    }
15812
15813
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
15814
0
    for (ImGuiWindow* window : src_node->Windows)
15815
0
    {
15816
0
        window->DockNode = NULL;
15817
0
        window->DockIsActive = false;
15818
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
15819
0
    }
15820
0
    src_node->Windows.clear();
15821
15822
0
    if (!move_tab_bar && src_node->TabBar)
15823
0
    {
15824
0
        if (dst_node->TabBar)
15825
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
15826
0
        DockNodeRemoveTabBar(src_node);
15827
0
    }
15828
0
}
15829
15830
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
15831
0
{
15832
0
    for (int n = 0; n < node->Windows.Size; n++)
15833
0
    {
15834
0
        SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
15835
0
        SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always);
15836
0
    }
15837
0
}
15838
15839
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
15840
0
{
15841
0
    if (node->HostWindow)
15842
0
    {
15843
0
        if (node->HostWindow->DockNodeAsHost == node)
15844
0
            node->HostWindow->DockNodeAsHost = NULL;
15845
0
        node->HostWindow = NULL;
15846
0
    }
15847
15848
0
    if (node->Windows.Size == 1)
15849
0
    {
15850
0
        node->VisibleWindow = node->Windows[0];
15851
0
        node->Windows[0]->DockIsActive = false;
15852
0
    }
15853
15854
0
    if (node->TabBar)
15855
0
        DockNodeRemoveTabBar(node);
15856
0
}
15857
15858
// Search function called once by root node in DockNodeUpdate()
15859
struct ImGuiDockNodeTreeInfo
15860
{
15861
    ImGuiDockNode*      CentralNode;
15862
    ImGuiDockNode*      FirstNodeWithWindows;
15863
    int                 CountNodesWithWindows;
15864
    //ImGuiWindowClass  WindowClassForMerges;
15865
15866
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
15867
};
15868
15869
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
15870
0
{
15871
0
    if (node->Windows.Size > 0)
15872
0
    {
15873
0
        if (info->FirstNodeWithWindows == NULL)
15874
0
            info->FirstNodeWithWindows = node;
15875
0
        info->CountNodesWithWindows++;
15876
0
    }
15877
0
    if (node->IsCentralNode())
15878
0
    {
15879
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
15880
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
15881
0
        info->CentralNode = node;
15882
0
    }
15883
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
15884
0
        return;
15885
0
    if (node->ChildNodes[0])
15886
0
        DockNodeFindInfo(node->ChildNodes[0], info);
15887
0
    if (node->ChildNodes[1])
15888
0
        DockNodeFindInfo(node->ChildNodes[1], info);
15889
0
}
15890
15891
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
15892
0
{
15893
0
    IM_ASSERT(id != 0);
15894
0
    for (int n = 0; n < node->Windows.Size; n++)
15895
0
        if (node->Windows[n]->ID == id)
15896
0
            return node->Windows[n];
15897
0
    return NULL;
15898
0
}
15899
15900
// - Remove inactive windows/nodes.
15901
// - Update visibility flag.
15902
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
15903
0
{
15904
0
    ImGuiContext& g = *GImGui;
15905
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15906
15907
    // Inherit most flags
15908
0
    if (node->ParentNode)
15909
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
15910
15911
    // Recurse into children
15912
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
15913
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
15914
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
15915
0
    node->HasCentralNodeChild = false;
15916
0
    if (node->ChildNodes[0])
15917
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
15918
0
    if (node->ChildNodes[1])
15919
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
15920
15921
    // Remove inactive windows, collapse nodes
15922
    // Merge node flags overrides stored in windows
15923
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
15924
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
15925
0
    {
15926
0
        ImGuiWindow* window = node->Windows[window_n];
15927
0
        IM_ASSERT(window->DockNode == node);
15928
15929
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
15930
0
        bool remove = false;
15931
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
15932
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
15933
0
        remove |= (window->DockTabWantClose);
15934
0
        if (remove)
15935
0
        {
15936
0
            window->DockTabWantClose = false;
15937
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
15938
0
            {
15939
0
                DockNodeHideHostWindow(node);
15940
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15941
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
15942
0
                return;
15943
0
            }
15944
0
            DockNodeRemoveWindow(node, window, node->ID);
15945
0
            window_n--;
15946
0
            continue;
15947
0
        }
15948
15949
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
15950
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
15951
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
15952
0
    }
15953
0
    node->UpdateMergedFlags();
15954
15955
    // Auto-hide tab bar option
15956
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
15957
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
15958
0
        node->WantHiddenTabBarToggle = true;
15959
0
    node->WantHiddenTabBarUpdate = false;
15960
15961
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
15962
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
15963
0
        node->WantHiddenTabBarToggle = false;
15964
15965
    // Apply toggles at a single point of the frame (here!)
15966
0
    if (node->Windows.Size > 1)
15967
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15968
0
    else if (node->WantHiddenTabBarToggle)
15969
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
15970
0
    node->WantHiddenTabBarToggle = false;
15971
15972
0
    DockNodeUpdateVisibleFlag(node);
15973
0
}
15974
15975
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
15976
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
15977
0
{
15978
0
    node->HasCentralNodeChild = false;
15979
0
    if (node->ChildNodes[0])
15980
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
15981
0
    if (node->ChildNodes[1])
15982
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
15983
0
    if (node->IsRootNode())
15984
0
    {
15985
0
        ImGuiDockNode* mark_node = node->CentralNode;
15986
0
        while (mark_node)
15987
0
        {
15988
0
            mark_node->HasCentralNodeChild = true;
15989
0
            mark_node = mark_node->ParentNode;
15990
0
        }
15991
0
    }
15992
0
}
15993
15994
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
15995
0
{
15996
    // Update visibility flag
15997
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
15998
0
    is_visible |= (node->Windows.Size > 0);
15999
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
16000
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
16001
0
    node->IsVisible = is_visible;
16002
0
}
16003
16004
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
16005
0
{
16006
0
    ImGuiContext& g = *GImGui;
16007
0
    IM_ASSERT(node->WantMouseMove == true);
16008
0
    StartMouseMovingWindow(window);
16009
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
16010
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
16011
0
    node->WantMouseMove = false;
16012
0
}
16013
16014
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
16015
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
16016
0
{
16017
0
    DockNodeUpdateFlagsAndCollapse(node);
16018
16019
    // - Setup central node pointers
16020
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
16021
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
16022
0
    ImGuiDockNodeTreeInfo info;
16023
0
    DockNodeFindInfo(node, &info);
16024
0
    node->CentralNode = info.CentralNode;
16025
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
16026
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
16027
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
16028
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
16029
16030
    // Copy the window class from of our first window so it can be used for proper dock filtering.
16031
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
16032
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
16033
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
16034
0
    {
16035
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
16036
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
16037
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
16038
0
            {
16039
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
16040
0
                break;
16041
0
            }
16042
0
    }
16043
16044
0
    ImGuiDockNode* mark_node = node->CentralNode;
16045
0
    while (mark_node)
16046
0
    {
16047
0
        mark_node->HasCentralNodeChild = true;
16048
0
        mark_node = mark_node->ParentNode;
16049
0
    }
16050
0
}
16051
16052
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
16053
0
{
16054
    // Remove ourselves from any previous different host window
16055
    // This can happen if a user mistakenly does (see #4295 for details):
16056
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
16057
    //  - N+1: NewFrame()                   // will create floating host window for that node
16058
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
16059
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
16060
0
        node->HostWindow->DockNodeAsHost = NULL;
16061
16062
0
    host_window->DockNodeAsHost = node;
16063
0
    node->HostWindow = host_window;
16064
0
}
16065
16066
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
16067
0
{
16068
0
    ImGuiContext& g = *GImGui;
16069
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
16070
0
    node->LastFrameAlive = g.FrameCount;
16071
0
    node->IsBgDrawnThisFrame = false;
16072
16073
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
16074
0
    if (node->IsRootNode())
16075
0
        DockNodeUpdateForRootNode(node);
16076
16077
    // Remove tab bar if not needed
16078
0
    if (node->TabBar && node->IsNoTabBar())
16079
0
        DockNodeRemoveTabBar(node);
16080
16081
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
16082
0
    bool want_to_hide_host_window = false;
16083
0
    if (node->IsFloatingNode())
16084
0
    {
16085
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
16086
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
16087
0
                want_to_hide_host_window = true;
16088
0
        if (node->CountNodeWithWindows == 0)
16089
0
            want_to_hide_host_window = true;
16090
0
    }
16091
0
    if (want_to_hide_host_window)
16092
0
    {
16093
0
        if (node->Windows.Size == 1)
16094
0
        {
16095
            // Floating window pos/size is authoritative
16096
0
            ImGuiWindow* single_window = node->Windows[0];
16097
0
            node->Pos = single_window->Pos;
16098
0
            node->Size = single_window->SizeFull;
16099
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
16100
16101
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
16102
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
16103
0
                FocusWindow(single_window);
16104
0
            if (node->HostWindow)
16105
0
            {
16106
0
                single_window->Viewport = node->HostWindow->Viewport;
16107
0
                single_window->ViewportId = node->HostWindow->ViewportId;
16108
0
                if (node->HostWindow->ViewportOwned)
16109
0
                {
16110
0
                    single_window->Viewport->Window = single_window;
16111
0
                    single_window->ViewportOwned = true;
16112
0
                }
16113
0
            }
16114
0
        }
16115
16116
0
        DockNodeHideHostWindow(node);
16117
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16118
0
        node->WantCloseAll = false;
16119
0
        node->WantCloseTabId = 0;
16120
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
16121
0
        node->LastFrameActive = g.FrameCount;
16122
16123
0
        if (node->WantMouseMove && node->Windows.Size == 1)
16124
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
16125
0
        return;
16126
0
    }
16127
16128
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16129
    // while the expected visible window is resizing itself.
16130
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16131
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16132
    //   N+0: Begin(): window created (with no known size), node is created
16133
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16134
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16135
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16136
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16137
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
16138
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16139
0
    {
16140
0
        IM_ASSERT(node->Windows.Size > 0);
16141
0
        ImGuiWindow* ref_window = NULL;
16142
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16143
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
16144
0
        if (ref_window == NULL)
16145
0
            ref_window = node->Windows[0];
16146
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16147
0
        {
16148
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16149
0
            return;
16150
0
        }
16151
0
    }
16152
16153
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16154
16155
    // Decide if the node will have a close button and a window menu button
16156
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16157
0
    node->HasCloseButton = false;
16158
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16159
0
    {
16160
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16161
0
        ImGuiWindow* window = node->Windows[window_n];
16162
0
        node->HasCloseButton |= window->HasCloseButton;
16163
0
        window->DockIsActive = (node->Windows.Size > 1);
16164
0
    }
16165
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
16166
0
        node->HasCloseButton = false;
16167
16168
    // Bind or create host window
16169
0
    ImGuiWindow* host_window = NULL;
16170
0
    bool beginned_into_host_window = false;
16171
0
    if (node->IsDockSpace())
16172
0
    {
16173
        // [Explicit root dockspace node]
16174
0
        IM_ASSERT(node->HostWindow);
16175
0
        host_window = node->HostWindow;
16176
0
    }
16177
0
    else
16178
0
    {
16179
        // [Automatic root or child nodes]
16180
0
        if (node->IsRootNode() && node->IsVisible)
16181
0
        {
16182
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16183
16184
            // Sync Pos
16185
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
16186
0
                SetNextWindowPos(ref_window->Pos);
16187
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
16188
0
                SetNextWindowPos(node->Pos);
16189
16190
            // Sync Size
16191
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16192
0
                SetNextWindowSize(ref_window->SizeFull);
16193
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
16194
0
                SetNextWindowSize(node->Size);
16195
16196
            // Sync Collapsed
16197
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16198
0
                SetNextWindowCollapsed(ref_window->Collapsed);
16199
16200
            // Sync Viewport
16201
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
16202
0
                SetNextWindowViewport(ref_window->ViewportId);
16203
16204
0
            SetNextWindowClass(&node->WindowClass);
16205
16206
            // Begin into the host window
16207
0
            char window_label[20];
16208
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
16209
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
16210
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
16211
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
16212
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
16213
16214
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
16215
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
16216
0
            Begin(window_label, NULL, window_flags);
16217
0
            PopStyleVar();
16218
0
            beginned_into_host_window = true;
16219
16220
0
            host_window = g.CurrentWindow;
16221
0
            DockNodeSetupHostWindow(node, host_window);
16222
0
            host_window->DC.CursorPos = host_window->Pos;
16223
0
            node->Pos = host_window->Pos;
16224
0
            node->Size = host_window->Size;
16225
16226
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
16227
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
16228
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
16229
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
16230
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
16231
            // after the dock host window, losing their top-most status.
16232
0
            if (node->HostWindow->Appearing)
16233
0
                BringWindowToDisplayFront(node->HostWindow);
16234
16235
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16236
0
        }
16237
0
        else if (node->ParentNode)
16238
0
        {
16239
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
16240
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16241
0
        }
16242
0
        if (node->WantMouseMove && node->HostWindow)
16243
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
16244
0
    }
16245
16246
    // Update focused node (the one whose title bar is highlight) within a node tree
16247
0
    if (node->IsSplitNode())
16248
0
        IM_ASSERT(node->TabBar == NULL);
16249
0
    if (node->IsRootNode())
16250
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
16251
0
            while (p_window != NULL && p_window->DockNode != NULL)
16252
0
            {
16253
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
16254
0
                if (p_node == node)
16255
0
                {
16256
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
16257
0
                    break;
16258
0
                }
16259
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
16260
0
            }
16261
16262
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
16263
0
    ImGuiDockNode* central_node = node->CentralNode;
16264
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
16265
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
16266
0
    if (central_node_hole)
16267
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
16268
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
16269
0
                central_node_hole_register_hit_test_hole = false;
16270
0
    if (central_node_hole_register_hit_test_hole)
16271
0
    {
16272
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
16273
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
16274
        // covering passthru node we'd have a gap on the edge not covered by the hole)
16275
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
16276
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
16277
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
16278
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
16279
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
16280
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
16281
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
16282
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
16283
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
16284
0
        if (central_node_hole && !hole_rect.IsInverted())
16285
0
        {
16286
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16287
0
            if (host_window->ParentWindow)
16288
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16289
0
        }
16290
0
    }
16291
16292
    // Update position/size, process and draw resizing splitters
16293
0
    if (node->IsRootNode() && host_window)
16294
0
    {
16295
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
16296
0
        DockNodeTreeUpdateSplitter(node);
16297
0
    }
16298
16299
    // Draw empty node background (currently can only be the Central Node)
16300
0
    if (host_window && node->IsEmpty() && node->IsVisible)
16301
0
    {
16302
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16303
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
16304
0
        if (node->LastBgColor != 0)
16305
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
16306
0
        node->IsBgDrawnThisFrame = true;
16307
0
    }
16308
16309
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
16310
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
16311
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
16312
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
16313
0
    if (render_dockspace_bg && node->IsVisible)
16314
0
    {
16315
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16316
0
        if (central_node_hole)
16317
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
16318
0
        else
16319
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
16320
0
    }
16321
16322
    // Draw and populate Tab Bar
16323
0
    if (host_window)
16324
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
16325
0
    if (host_window && node->Windows.Size > 0)
16326
0
    {
16327
0
        DockNodeUpdateTabBar(node, host_window);
16328
0
    }
16329
0
    else
16330
0
    {
16331
0
        node->WantCloseAll = false;
16332
0
        node->WantCloseTabId = 0;
16333
0
        node->IsFocused = false;
16334
0
    }
16335
0
    if (node->TabBar && node->TabBar->SelectedTabId)
16336
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
16337
0
    else if (node->Windows.Size > 0)
16338
0
        node->SelectedTabId = node->Windows[0]->TabId;
16339
16340
    // Draw payload drop target
16341
0
    if (host_window && node->IsVisible)
16342
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
16343
0
            BeginDockableDragDropTarget(host_window);
16344
16345
    // We update this after DockNodeUpdateTabBar()
16346
0
    node->LastFrameActive = g.FrameCount;
16347
16348
    // Recurse into children
16349
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
16350
0
    if (host_window)
16351
0
    {
16352
0
        if (node->ChildNodes[0])
16353
0
            DockNodeUpdate(node->ChildNodes[0]);
16354
0
        if (node->ChildNodes[1])
16355
0
            DockNodeUpdate(node->ChildNodes[1]);
16356
16357
        // Render outer borders last (after the tab bar)
16358
0
        if (node->IsRootNode())
16359
0
            RenderWindowOuterBorders(host_window);
16360
0
    }
16361
16362
    // End host window
16363
0
    if (beginned_into_host_window) //-V1020
16364
0
        End();
16365
0
}
16366
16367
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
16368
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
16369
0
{
16370
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
16371
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
16372
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
16373
0
        return d;
16374
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
16375
0
}
16376
16377
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
16378
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
16379
// Custom overrides may want to decorate, group, sort entries.
16380
// Please note those are internal structures: if you copy this expect occasional breakage.
16381
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16382
0
{
16383
0
    IM_UNUSED(ctx);
16384
0
    if (tab_bar->Tabs.Size == 1)
16385
0
    {
16386
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
16387
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
16388
0
            node->WantHiddenTabBarToggle = true;
16389
0
    }
16390
0
    else
16391
0
    {
16392
        // Display a selectable list of windows in this docking node
16393
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16394
0
        {
16395
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16396
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
16397
0
                continue;
16398
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
16399
0
                TabBarQueueFocus(tab_bar, tab);
16400
0
            SameLine();
16401
0
            Text("   ");
16402
0
        }
16403
0
    }
16404
0
}
16405
16406
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16407
0
{
16408
    // Try to position the menu so it is more likely to stays within the same viewport
16409
0
    ImGuiContext& g = *GImGui;
16410
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
16411
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
16412
0
    else
16413
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
16414
0
    if (BeginPopup("#WindowMenu"))
16415
0
    {
16416
0
        node->IsFocused = true;
16417
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
16418
0
        EndPopup();
16419
0
    }
16420
0
}
16421
16422
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
16423
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
16424
0
{
16425
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
16426
0
        return false;
16427
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
16428
0
        return false;
16429
0
    Begin(node->HostWindow->Name);
16430
0
    PushOverrideID(node->ID);
16431
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node);
16432
0
    IM_UNUSED(ret);
16433
0
    IM_ASSERT(ret);
16434
0
    return true;
16435
0
}
16436
16437
void ImGui::DockNodeEndAmendTabBar()
16438
0
{
16439
0
    EndTabBar();
16440
0
    PopID();
16441
0
    End();
16442
0
}
16443
16444
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
16445
0
{
16446
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
16447
0
    ImGuiContext& g = *GImGui;
16448
0
    if (g.NavWindowingTarget)
16449
0
        return (g.NavWindowingTarget->DockNode == node);
16450
16451
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
16452
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
16453
0
    {
16454
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
16455
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
16456
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
16457
0
            parent_window = parent_window->ParentWindow->RootWindow;
16458
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
16459
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
16460
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
16461
0
                return true;
16462
0
    }
16463
0
    return false;
16464
0
}
16465
16466
// Submit the tab bar corresponding to a dock node and various housekeeping details.
16467
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
16468
0
{
16469
0
    ImGuiContext& g = *GImGui;
16470
0
    ImGuiStyle& style = g.Style;
16471
16472
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16473
0
    const bool closed_all = node->WantCloseAll && node_was_active;
16474
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
16475
0
    node->WantCloseAll = false;
16476
0
    node->WantCloseTabId = 0;
16477
16478
    // Decide if we should use a focused title bar color
16479
0
    bool is_focused = false;
16480
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16481
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
16482
0
        is_focused = true;
16483
16484
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16485
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16486
0
    {
16487
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16488
0
        node->IsFocused = is_focused;
16489
0
        if (is_focused)
16490
0
            node->LastFrameFocused = g.FrameCount;
16491
0
        if (node->VisibleWindow)
16492
0
        {
16493
            // Notify root of visible window (used to display title in OS task bar)
16494
0
            if (is_focused || root_node->VisibleWindow == NULL)
16495
0
                root_node->VisibleWindow = node->VisibleWindow;
16496
0
            if (node->TabBar)
16497
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16498
0
        }
16499
0
        return;
16500
0
    }
16501
16502
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16503
0
    bool backup_skip_item = host_window->SkipItems;
16504
0
    if (!node->IsDockSpace())
16505
0
    {
16506
0
        host_window->SkipItems = false;
16507
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16508
0
    }
16509
16510
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16511
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16512
    // as docked windows themselves will override the stack with their own root ID.
16513
0
    PushOverrideID(node->ID);
16514
0
    ImGuiTabBar* tab_bar = node->TabBar;
16515
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16516
0
    if (tab_bar == NULL)
16517
0
    {
16518
0
        DockNodeAddTabBar(node);
16519
0
        tab_bar = node->TabBar;
16520
0
    }
16521
16522
0
    ImGuiID focus_tab_id = 0;
16523
0
    node->IsFocused = is_focused;
16524
16525
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16526
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16527
16528
    // In a dock node, the Collapse Button turns into the Window Menu button.
16529
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
16530
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
16531
0
    {
16532
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
16533
0
        DockNodeWindowMenuUpdate(node, tab_bar);
16534
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
16535
0
            focus_tab_id = tab_bar->NextSelectedTabId;
16536
0
        is_focused |= node->IsFocused;
16537
0
    }
16538
16539
    // Layout
16540
0
    ImRect title_bar_rect, tab_bar_rect;
16541
0
    ImVec2 window_menu_button_pos;
16542
0
    ImVec2 close_button_pos;
16543
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
16544
16545
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
16546
0
    const int tabs_count_old = tab_bar->Tabs.Size;
16547
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16548
0
    {
16549
0
        ImGuiWindow* window = node->Windows[window_n];
16550
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
16551
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
16552
0
    }
16553
16554
    // Title bar
16555
0
    if (is_focused)
16556
0
        node->LastFrameFocused = g.FrameCount;
16557
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
16558
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE);
16559
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
16560
16561
    // Docking/Collapse button
16562
0
    if (has_window_menu_button)
16563
0
    {
16564
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
16565
0
            OpenPopup("#WindowMenu");
16566
0
        if (IsItemActive())
16567
0
            focus_tab_id = tab_bar->SelectedTabId;
16568
0
    }
16569
16570
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
16571
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
16572
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
16573
0
    {
16574
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
16575
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
16576
0
        tabs_unsorted_start = tab_n;
16577
0
    }
16578
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
16579
0
    {
16580
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
16581
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
16582
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder);
16583
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
16584
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
16585
0
    }
16586
16587
    // Apply NavWindow focus back to the tab bar
16588
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
16589
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
16590
16591
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
16592
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
16593
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
16594
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
16595
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
16596
16597
    // Begin tab bar
16598
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
16599
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
16600
0
    if (!host_window->Collapsed && is_focused)
16601
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
16602
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
16603
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
16604
16605
    // Backup style colors
16606
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
16607
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16608
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
16609
16610
    // Submit actual tabs
16611
0
    node->VisibleWindow = NULL;
16612
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16613
0
    {
16614
0
        ImGuiWindow* window = node->Windows[window_n];
16615
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
16616
0
            continue;
16617
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
16618
0
        {
16619
0
            ImGuiTabItemFlags tab_item_flags = 0;
16620
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
16621
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
16622
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
16623
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
16624
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
16625
16626
            // Apply stored style overrides for the window
16627
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16628
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
16629
16630
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
16631
0
            bool tab_open = true;
16632
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
16633
0
            if (!tab_open)
16634
0
                node->WantCloseTabId = window->TabId;
16635
0
            if (tab_bar->VisibleTabId == window->TabId)
16636
0
                node->VisibleWindow = window;
16637
16638
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
16639
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
16640
0
            window->DockTabItemRect = g.LastItemData.Rect;
16641
16642
            // Update navigation ID on menu layer
16643
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
16644
0
                host_window->NavLastIds[1] = window->TabId;
16645
0
        }
16646
0
    }
16647
16648
    // Restore style colors
16649
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16650
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
16651
16652
    // Notify root of visible window (used to display title in OS task bar)
16653
0
    if (node->VisibleWindow)
16654
0
        if (is_focused || root_node->VisibleWindow == NULL)
16655
0
            root_node->VisibleWindow = node->VisibleWindow;
16656
16657
    // Close button (after VisibleWindow was updated)
16658
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
16659
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
16660
0
    const bool close_button_is_visible = node->HasCloseButton;
16661
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
16662
0
    if (close_button_is_visible)
16663
0
    {
16664
0
        if (!close_button_is_enabled)
16665
0
        {
16666
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
16667
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
16668
0
        }
16669
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
16670
0
        {
16671
0
            node->WantCloseAll = true;
16672
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
16673
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
16674
0
        }
16675
        //if (IsItemActive())
16676
        //    focus_tab_id = tab_bar->SelectedTabId;
16677
0
        if (!close_button_is_enabled)
16678
0
        {
16679
0
            PopStyleColor();
16680
0
            PopItemFlag();
16681
0
        }
16682
0
    }
16683
16684
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
16685
    // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held)
16686
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
16687
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
16688
0
    {
16689
0
        bool held;
16690
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowItemOverlap);
16691
0
        if (g.HoveredId == title_bar_id)
16692
0
        {
16693
            // ImGuiButtonFlags_AllowItemOverlap + SetItemAllowOverlap() required for appending into dock node tab bar,
16694
            // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
16695
0
            g.LastItemData.ID = title_bar_id;
16696
0
            SetItemAllowOverlap();
16697
0
        }
16698
0
        if (held)
16699
0
        {
16700
0
            if (IsMouseClicked(0))
16701
0
                focus_tab_id = tab_bar->SelectedTabId;
16702
16703
            // Forward moving request to selected window
16704
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
16705
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false);
16706
0
        }
16707
0
    }
16708
16709
    // Forward focus from host node to selected window
16710
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
16711
    //    focus_tab_id = tab_bar->SelectedTabId;
16712
16713
    // When clicked on a tab we requested focus to the docked child
16714
    // This overrides the value set by "forward focus from host node to selected window".
16715
0
    if (tab_bar->NextSelectedTabId)
16716
0
        focus_tab_id = tab_bar->NextSelectedTabId;
16717
16718
    // Apply navigation focus
16719
0
    if (focus_tab_id != 0)
16720
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
16721
0
            if (tab->Window)
16722
0
            {
16723
0
                FocusWindow(tab->Window);
16724
0
                NavInitWindow(tab->Window, false);
16725
0
            }
16726
16727
0
    EndTabBar();
16728
0
    PopID();
16729
16730
    // Restore SkipItems flag
16731
0
    if (!node->IsDockSpace())
16732
0
    {
16733
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
16734
0
        host_window->SkipItems = backup_skip_item;
16735
0
    }
16736
0
}
16737
16738
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
16739
0
{
16740
0
    IM_ASSERT(node->TabBar == NULL);
16741
0
    node->TabBar = IM_NEW(ImGuiTabBar);
16742
0
}
16743
16744
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
16745
0
{
16746
0
    if (node->TabBar == NULL)
16747
0
        return;
16748
0
    IM_DELETE(node->TabBar);
16749
0
    node->TabBar = NULL;
16750
0
}
16751
16752
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
16753
0
{
16754
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
16755
0
        return false;
16756
16757
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
16758
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
16759
0
    if (host_class->ClassId != payload_class->ClassId)
16760
0
    {
16761
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
16762
0
            return true;
16763
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
16764
0
            return true;
16765
0
        return false;
16766
0
    }
16767
16768
    // Prevent docking any window created above a popup
16769
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
16770
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
16771
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
16772
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
16773
0
    ImGuiContext& g = *GImGui;
16774
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
16775
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
16776
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
16777
0
                return false;
16778
16779
0
    return true;
16780
0
}
16781
16782
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
16783
0
{
16784
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
16785
0
        return true;
16786
16787
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
16788
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
16789
0
    {
16790
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
16791
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
16792
0
            return true;
16793
0
    }
16794
0
    return false;
16795
0
}
16796
16797
// window menu button == collapse button when not in a dock node.
16798
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
16799
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
16800
0
{
16801
0
    ImGuiContext& g = *GImGui;
16802
0
    ImGuiStyle& style = g.Style;
16803
16804
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
16805
0
    if (out_title_rect) { *out_title_rect = r; }
16806
16807
0
    r.Min.x += style.WindowBorderSize;
16808
0
    r.Max.x -= style.WindowBorderSize;
16809
16810
0
    float button_sz = g.FontSize;
16811
16812
0
    ImVec2 window_menu_button_pos = r.Min;
16813
0
    r.Min.x += style.FramePadding.x;
16814
0
    r.Max.x -= style.FramePadding.x;
16815
0
    if (node->HasCloseButton)
16816
0
    {
16817
0
        r.Max.x -= button_sz;
16818
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - style.FramePadding.x, r.Min.y);
16819
0
    }
16820
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
16821
0
    {
16822
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
16823
0
    }
16824
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
16825
0
    {
16826
0
        r.Max.x -= button_sz + style.FramePadding.x;
16827
0
        window_menu_button_pos = ImVec2(r.Max.x, r.Min.y);
16828
0
    }
16829
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
16830
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
16831
0
}
16832
16833
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
16834
0
{
16835
0
    ImGuiContext& g = *GImGui;
16836
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
16837
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16838
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
16839
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
16840
16841
    // Distribute size on given axis (with a desired size or equally)
16842
0
    const float w_avail = size_old[axis] - dock_spacing;
16843
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
16844
0
    {
16845
0
        size_new[axis] = size_new_desired[axis];
16846
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16847
0
    }
16848
0
    else
16849
0
    {
16850
0
        size_new[axis] = IM_FLOOR(w_avail * 0.5f);
16851
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16852
0
    }
16853
16854
    // Position each node
16855
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
16856
0
    {
16857
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
16858
0
    }
16859
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
16860
0
    {
16861
0
        pos_new[axis] = pos_old[axis];
16862
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
16863
0
    }
16864
0
}
16865
16866
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
16867
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
16868
0
{
16869
0
    ImGuiContext& g = *GImGui;
16870
16871
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
16872
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
16873
0
    float hs_w; // Half-size, longer axis
16874
0
    float hs_h; // Half-size, smaller axis
16875
0
    ImVec2 off; // Distance from edge or center
16876
0
    if (outer_docking)
16877
0
    {
16878
        //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
16879
        //hs_h = ImFloor(hs_w * 0.15f);
16880
        //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
16881
0
        hs_w = ImFloor(hs_for_central_nodes * 1.50f);
16882
0
        hs_h = ImFloor(hs_for_central_nodes * 0.80f);
16883
0
        off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h));
16884
0
    }
16885
0
    else
16886
0
    {
16887
0
        hs_w = ImFloor(hs_for_central_nodes);
16888
0
        hs_h = ImFloor(hs_for_central_nodes * 0.90f);
16889
0
        off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
16890
0
    }
16891
16892
0
    ImVec2 c = ImFloor(parent.GetCenter());
16893
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
16894
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
16895
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
16896
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
16897
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
16898
16899
0
    if (test_mouse_pos == NULL)
16900
0
        return false;
16901
16902
0
    ImRect hit_r = out_r;
16903
0
    if (!outer_docking)
16904
0
    {
16905
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
16906
0
        hit_r.Expand(ImFloor(hs_w * 0.30f));
16907
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
16908
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
16909
0
        float r_threshold_center = hs_w * 1.4f;
16910
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
16911
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
16912
0
            return (dir == ImGuiDir_None);
16913
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
16914
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
16915
0
    }
16916
0
    return hit_r.Contains(*test_mouse_pos);
16917
0
}
16918
16919
// host_node may be NULL if the window doesn't have a DockNode already.
16920
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
16921
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
16922
0
{
16923
0
    ImGuiContext& g = *GImGui;
16924
16925
    // There is an edge case when docking into a dockspace which only has inactive nodes.
16926
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
16927
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
16928
0
    if (payload_node == NULL)
16929
0
        payload_node = payload_window->DockNodeAsHost;
16930
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
16931
0
    if (ref_node_for_rect)
16932
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
16933
16934
    // Filter, figure out where we are allowed to dock
16935
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
16936
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
16937
0
    data->IsCenterAvailable = true;
16938
0
    if (is_outer_docking)
16939
0
        data->IsCenterAvailable = false;
16940
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking)
16941
0
        data->IsCenterAvailable = false;
16942
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode())
16943
0
        data->IsCenterAvailable = false;
16944
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
16945
0
        data->IsCenterAvailable = false;
16946
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
16947
0
        data->IsCenterAvailable = false;
16948
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
16949
0
        data->IsCenterAvailable = false;
16950
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
16951
0
        data->IsCenterAvailable = false;
16952
16953
0
    data->IsSidesAvailable = true;
16954
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit)
16955
0
        data->IsSidesAvailable = false;
16956
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
16957
0
        data->IsSidesAvailable = false;
16958
0
    else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther))
16959
0
        data->IsSidesAvailable = false;
16960
16961
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
16962
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
16963
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
16964
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
16965
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
16966
16967
    // Calculate drop shapes geometry for allowed splitting directions
16968
0
    IM_ASSERT(ImGuiDir_None == -1);
16969
0
    data->SplitNode = host_node;
16970
0
    data->SplitDir = ImGuiDir_None;
16971
0
    data->IsSplitDirExplicit = false;
16972
0
    if (!host_window->Collapsed)
16973
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
16974
0
        {
16975
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
16976
0
                continue;
16977
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
16978
0
                continue;
16979
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
16980
0
            {
16981
0
                data->SplitDir = (ImGuiDir)dir;
16982
0
                data->IsSplitDirExplicit = true;
16983
0
            }
16984
0
        }
16985
16986
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
16987
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
16988
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
16989
0
        data->IsDropAllowed = false;
16990
16991
    // Calculate split area
16992
0
    data->SplitRatio = 0.0f;
16993
0
    if (data->SplitDir != ImGuiDir_None)
16994
0
    {
16995
0
        ImGuiDir split_dir = data->SplitDir;
16996
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16997
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
16998
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
16999
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
17000
17001
        // Calculate split ratio so we can pass it down the docking request
17002
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
17003
0
        data->FutureNode.Pos = pos_new;
17004
0
        data->FutureNode.Size = size_new;
17005
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
17006
0
    }
17007
0
}
17008
17009
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
17010
0
{
17011
0
    ImGuiContext& g = *GImGui;
17012
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
17013
17014
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
17015
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
17016
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
17017
17018
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
17019
0
    int overlay_draw_lists_count = 0;
17020
0
    ImDrawList* overlay_draw_lists[2];
17021
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
17022
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
17023
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
17024
17025
    // Draw main preview rectangle
17026
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
17027
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
17028
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
17029
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
17030
17031
    // Display area preview
17032
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
17033
0
    if (data->IsDropAllowed)
17034
0
    {
17035
0
        ImRect overlay_rect = data->FutureNode.Rect();
17036
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
17037
0
            overlay_rect.Min.y += GetFrameHeight();
17038
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
17039
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17040
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE));
17041
0
    }
17042
17043
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
17044
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
17045
0
    {
17046
        // Compute target tab bar geometry so we can locate our preview tabs
17047
0
        ImRect tab_bar_rect;
17048
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
17049
0
        ImVec2 tab_pos = tab_bar_rect.Min;
17050
0
        if (host_node && host_node->TabBar)
17051
0
        {
17052
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
17053
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
17054
0
            else
17055
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
17056
0
        }
17057
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
17058
0
        {
17059
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
17060
0
        }
17061
17062
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
17063
0
        if (root_payload->DockNodeAsHost)
17064
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
17065
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
17066
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
17067
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
17068
0
        {
17069
            // DockNode's TabBar may have non-window Tabs manually appended by user
17070
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
17071
0
            if (tab_bar_with_payload && payload_window == NULL)
17072
0
                continue;
17073
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
17074
0
                continue;
17075
17076
            // Calculate the tab bounding box for each payload window
17077
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
17078
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
17079
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
17080
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
17081
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
17082
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
17083
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17084
0
            {
17085
0
                ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
17086
0
                if (!tab_bar_rect.Contains(tab_bb))
17087
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
17088
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
17089
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
17090
0
                if (!tab_bar_rect.Contains(tab_bb))
17091
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
17092
0
            }
17093
0
            PopStyleColor();
17094
0
        }
17095
0
    }
17096
17097
    // Display drop boxes
17098
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
17099
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17100
0
    {
17101
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
17102
0
        {
17103
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
17104
0
            ImRect draw_r_in = draw_r;
17105
0
            draw_r_in.Expand(-2.0f);
17106
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
17107
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17108
0
            {
17109
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
17110
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
17111
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
17112
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
17113
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
17114
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
17115
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
17116
0
            }
17117
0
        }
17118
17119
        // Stop after ImGuiDir_None
17120
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
17121
0
            return;
17122
0
    }
17123
0
}
17124
17125
//-----------------------------------------------------------------------------
17126
// Docking: ImGuiDockNode Tree manipulation functions
17127
//-----------------------------------------------------------------------------
17128
// - DockNodeTreeSplit()
17129
// - DockNodeTreeMerge()
17130
// - DockNodeTreeUpdatePosSize()
17131
// - DockNodeTreeUpdateSplitterFindTouchingNode()
17132
// - DockNodeTreeUpdateSplitter()
17133
// - DockNodeTreeFindFallbackLeafNode()
17134
// - DockNodeTreeFindNodeByPos()
17135
//-----------------------------------------------------------------------------
17136
17137
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17138
0
{
17139
0
    ImGuiContext& g = *GImGui;
17140
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
17141
17142
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
17143
0
    child_0->ParentNode = parent_node;
17144
17145
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
17146
0
    child_1->ParentNode = parent_node;
17147
17148
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
17149
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
17150
0
    parent_node->ChildNodes[0] = child_0;
17151
0
    parent_node->ChildNodes[1] = child_1;
17152
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
17153
0
    parent_node->SplitAxis = split_axis;
17154
0
    parent_node->VisibleWindow = NULL;
17155
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17156
17157
0
    float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE);
17158
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
17159
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
17160
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
17161
0
    child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
17162
0
    child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
17163
17164
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
17165
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
17166
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
17167
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
17168
17169
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
17170
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17171
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17172
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17173
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17174
0
    child_0->UpdateMergedFlags();
17175
0
    child_1->UpdateMergedFlags();
17176
0
    parent_node->UpdateMergedFlags();
17177
0
    if (child_inheritor->IsCentralNode())
17178
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
17179
0
}
17180
17181
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
17182
0
{
17183
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
17184
0
    ImGuiContext& g = *GImGui;
17185
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
17186
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
17187
0
    IM_ASSERT(child_0 || child_1);
17188
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
17189
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
17190
0
    {
17191
0
        IM_ASSERT(parent_node->TabBar == NULL);
17192
0
        IM_ASSERT(parent_node->Windows.Size == 0);
17193
0
    }
17194
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
17195
17196
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
17197
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
17198
0
    if (child_0)
17199
0
    {
17200
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
17201
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
17202
0
    }
17203
0
    if (child_1)
17204
0
    {
17205
0
        DockNodeMoveWindows(parent_node, child_1);
17206
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
17207
0
    }
17208
0
    DockNodeApplyPosSizeToWindows(parent_node);
17209
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17210
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
17211
0
    parent_node->SizeRef = backup_last_explicit_size;
17212
17213
    // Flags transfer
17214
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
17215
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17216
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17217
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
17218
0
    parent_node->UpdateMergedFlags();
17219
17220
0
    if (child_0)
17221
0
    {
17222
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
17223
0
        IM_DELETE(child_0);
17224
0
    }
17225
0
    if (child_1)
17226
0
    {
17227
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
17228
0
        IM_DELETE(child_1);
17229
0
    }
17230
0
}
17231
17232
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
17233
// (Depth-first, Pre-Order)
17234
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
17235
0
{
17236
    // During the regular dock node update we write to all nodes.
17237
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
17238
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
17239
0
    if (write_to_node)
17240
0
    {
17241
0
        node->Pos = pos;
17242
0
        node->Size = size;
17243
0
    }
17244
17245
0
    if (node->IsLeafNode())
17246
0
        return;
17247
17248
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17249
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17250
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
17251
0
    ImVec2 child_0_size = size, child_1_size = size;
17252
17253
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
17254
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
17255
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
17256
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
17257
17258
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
17259
0
    {
17260
0
        ImGuiContext& g = *GImGui;
17261
0
        const float spacing = DOCKING_SPLITTER_SIZE;
17262
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17263
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
17264
17265
        // Size allocation policy
17266
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
17267
0
        const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
17268
17269
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
17270
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImFloor()
17271
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
17272
17273
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
17274
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
17275
0
        {
17276
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
17277
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17278
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17279
0
        }
17280
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
17281
0
        {
17282
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
17283
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
17284
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17285
0
        }
17286
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
17287
0
        {
17288
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
17289
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
17290
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
17291
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * split_ratio);
17292
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17293
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17294
0
        }
17295
17296
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
17297
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
17298
0
        {
17299
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
17300
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17301
0
        }
17302
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
17303
0
        {
17304
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
17305
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
17306
0
        }
17307
0
        else
17308
0
        {
17309
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
17310
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
17311
0
            child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5f));
17312
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17313
0
        }
17314
17315
0
        child_1_pos[axis] += spacing + child_0_size[axis];
17316
0
    }
17317
17318
0
    if (only_write_to_single_node == NULL)
17319
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
17320
17321
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
17322
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
17323
0
    if (child_0_recurse)
17324
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
17325
0
    if (child_1_recurse)
17326
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
17327
0
}
17328
17329
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
17330
0
{
17331
0
    if (node->IsLeafNode())
17332
0
    {
17333
0
        touching_nodes->push_back(node);
17334
0
        return;
17335
0
    }
17336
0
    if (node->ChildNodes[0]->IsVisible)
17337
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
17338
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
17339
0
    if (node->ChildNodes[1]->IsVisible)
17340
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
17341
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
17342
0
}
17343
17344
// (Depth-First, Pre-Order)
17345
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
17346
0
{
17347
0
    if (node->IsLeafNode())
17348
0
        return;
17349
17350
0
    ImGuiContext& g = *GImGui;
17351
17352
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17353
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17354
0
    if (child_0->IsVisible && child_1->IsVisible)
17355
0
    {
17356
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
17357
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17358
0
        IM_ASSERT(axis != ImGuiAxis_None);
17359
0
        ImRect bb;
17360
0
        bb.Min = child_0->Pos;
17361
0
        bb.Max = child_1->Pos;
17362
0
        bb.Min[axis] += child_0->Size[axis];
17363
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
17364
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
17365
17366
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
17367
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
17368
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
17369
0
        {
17370
0
            ImGuiWindow* window = g.CurrentWindow;
17371
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
17372
0
        }
17373
0
        else
17374
0
        {
17375
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
17376
            //bb.Max[axis] -= 1;
17377
0
            PushID(node->ID);
17378
17379
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
17380
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
17381
0
            float min_size = g.Style.WindowMinSize[axis];
17382
0
            float resize_limits[2];
17383
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
17384
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
17385
17386
0
            ImGuiID splitter_id = GetID("##Splitter");
17387
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
17388
0
            {
17389
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
17390
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
17391
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
17392
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
17393
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
17394
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
17395
17396
                // [DEBUG] Render touching nodes & limits
17397
                /*
17398
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17399
                for (int n = 0; n < 2; n++)
17400
                {
17401
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
17402
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
17403
                    if (axis == ImGuiAxis_X)
17404
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
17405
                    else
17406
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
17407
                }
17408
                */
17409
0
            }
17410
17411
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
17412
0
            float cur_size_0 = child_0->Size[axis];
17413
0
            float cur_size_1 = child_1->Size[axis];
17414
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
17415
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
17416
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
17417
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
17418
0
            {
17419
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
17420
0
                {
17421
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
17422
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
17423
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
17424
17425
                    // Lock the size of every node that is a sibling of the node we are touching
17426
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
17427
0
                    for (int side_n = 0; side_n < 2; side_n++)
17428
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
17429
0
                        {
17430
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
17431
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17432
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
17433
0
                            while (touching_node->ParentNode != node)
17434
0
                            {
17435
0
                                if (touching_node->ParentNode->SplitAxis == axis)
17436
0
                                {
17437
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
17438
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
17439
0
                                    node_to_preserve->WantLockSizeOnce = true;
17440
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
17441
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
17442
0
                                }
17443
0
                                touching_node = touching_node->ParentNode;
17444
0
                            }
17445
0
                        }
17446
17447
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
17448
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
17449
0
                    MarkIniSettingsDirty();
17450
0
                }
17451
0
            }
17452
0
            PopID();
17453
0
        }
17454
0
    }
17455
17456
0
    if (child_0->IsVisible)
17457
0
        DockNodeTreeUpdateSplitter(child_0);
17458
0
    if (child_1->IsVisible)
17459
0
        DockNodeTreeUpdateSplitter(child_1);
17460
0
}
17461
17462
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
17463
0
{
17464
0
    if (node->IsLeafNode())
17465
0
        return node;
17466
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
17467
0
        return leaf_node;
17468
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
17469
0
        return leaf_node;
17470
0
    return NULL;
17471
0
}
17472
17473
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
17474
0
{
17475
0
    if (!node->IsVisible)
17476
0
        return NULL;
17477
17478
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
17479
0
    ImRect r(node->Pos, node->Pos + node->Size);
17480
0
    r.Expand(dock_spacing * 0.5f);
17481
0
    bool inside = r.Contains(pos);
17482
0
    if (!inside)
17483
0
        return NULL;
17484
17485
0
    if (node->IsLeafNode())
17486
0
        return node;
17487
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17488
0
        return hovered_node;
17489
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17490
0
        return hovered_node;
17491
17492
    // This means we are hovering over the splitter/spacing of a parent node
17493
0
    return node;
17494
0
}
17495
17496
//-----------------------------------------------------------------------------
17497
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17498
//-----------------------------------------------------------------------------
17499
// - SetWindowDock() [Internal]
17500
// - DockSpace()
17501
// - DockSpaceOverViewport()
17502
//-----------------------------------------------------------------------------
17503
17504
// [Internal] Called via SetNextWindowDockID()
17505
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17506
0
{
17507
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17508
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17509
0
        return;
17510
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17511
17512
0
    if (window->DockId == dock_id)
17513
0
        return;
17514
17515
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17516
0
    ImGuiContext* ctx = GImGui;
17517
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
17518
0
        if (new_node->IsSplitNode())
17519
0
        {
17520
            // Policy: Find central node or latest focused node. We first move back to our root node.
17521
0
            new_node = DockNodeGetRootNode(new_node);
17522
0
            if (new_node->CentralNode)
17523
0
            {
17524
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
17525
0
                dock_id = new_node->CentralNode->ID;
17526
0
            }
17527
0
            else
17528
0
            {
17529
0
                dock_id = new_node->LastFocusedNodeId;
17530
0
            }
17531
0
        }
17532
17533
0
    if (window->DockId == dock_id)
17534
0
        return;
17535
17536
0
    if (window->DockNode)
17537
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
17538
0
    window->DockId = dock_id;
17539
0
}
17540
17541
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
17542
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
17543
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
17544
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
17545
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
17546
0
{
17547
0
    ImGuiContext* ctx = GImGui;
17548
0
    ImGuiContext& g = *ctx;
17549
0
    ImGuiWindow* window = GetCurrentWindowRead();
17550
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17551
0
        return 0;
17552
17553
    // Early out if parent window is hidden/collapsed
17554
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
17555
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
17556
0
    if (window->SkipItems)
17557
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
17558
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
17559
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
17560
17561
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
17562
0
    IM_ASSERT(id != 0);
17563
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
17564
0
    if (!node)
17565
0
    {
17566
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
17567
0
        node = DockContextAddNode(ctx, id);
17568
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
17569
0
    }
17570
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
17571
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
17572
0
    node->SharedFlags = flags;
17573
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
17574
17575
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
17576
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
17577
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
17578
0
    {
17579
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
17580
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17581
0
        return id;
17582
0
    }
17583
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17584
17585
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
17586
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
17587
0
    {
17588
0
        node->LastFrameAlive = g.FrameCount;
17589
0
        return id;
17590
0
    }
17591
17592
0
    const ImVec2 content_avail = GetContentRegionAvail();
17593
0
    ImVec2 size = ImFloor(size_arg);
17594
0
    if (size.x <= 0.0f)
17595
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
17596
0
    if (size.y <= 0.0f)
17597
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
17598
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17599
17600
0
    node->Pos = window->DC.CursorPos;
17601
0
    node->Size = node->SizeRef = size;
17602
0
    SetNextWindowPos(node->Pos);
17603
0
    SetNextWindowSize(node->Size);
17604
0
    g.NextWindowData.PosUndock = false;
17605
17606
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
17607
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
17608
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
17609
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
17610
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
17611
0
    window_flags |= ImGuiWindowFlags_NoBackground;
17612
17613
0
    char title[256];
17614
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
17615
17616
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
17617
0
    Begin(title, NULL, window_flags);
17618
0
    PopStyleVar();
17619
17620
0
    ImGuiWindow* host_window = g.CurrentWindow;
17621
0
    DockNodeSetupHostWindow(node, host_window);
17622
0
    host_window->ChildId = window->GetID(title);
17623
0
    node->OnlyNodeWithWindows = NULL;
17624
17625
0
    IM_ASSERT(node->IsRootNode());
17626
17627
    // We need to handle the rare case were a central node is missing.
17628
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
17629
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
17630
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
17631
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
17632
    // as it doesn't make sense for an empty dockspace to not have this property.
17633
0
    if (node->IsLeafNode() && !node->IsCentralNode())
17634
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17635
17636
    // Update the node
17637
0
    DockNodeUpdate(node);
17638
17639
0
    End();
17640
17641
0
    ImRect bb(node->Pos, node->Pos + size);
17642
0
    ItemSize(size);
17643
0
    ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
17644
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
17645
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
17646
17647
0
    return id;
17648
0
}
17649
17650
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
17651
// The limitation with this call is that your window won't have a menu bar.
17652
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
17653
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
17654
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
17655
0
{
17656
0
    if (viewport == NULL)
17657
0
        viewport = GetMainViewport();
17658
17659
0
    SetNextWindowPos(viewport->WorkPos);
17660
0
    SetNextWindowSize(viewport->WorkSize);
17661
0
    SetNextWindowViewport(viewport->ID);
17662
17663
0
    ImGuiWindowFlags host_window_flags = 0;
17664
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
17665
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
17666
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
17667
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
17668
17669
0
    char label[32];
17670
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
17671
17672
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
17673
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
17674
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
17675
0
    Begin(label, NULL, host_window_flags);
17676
0
    PopStyleVar(3);
17677
17678
0
    ImGuiID dockspace_id = GetID("DockSpace");
17679
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
17680
0
    End();
17681
17682
0
    return dockspace_id;
17683
0
}
17684
17685
//-----------------------------------------------------------------------------
17686
// Docking: Builder Functions
17687
//-----------------------------------------------------------------------------
17688
// Very early end-user API to manipulate dock nodes.
17689
// Only available in imgui_internal.h. Expect this API to change/break!
17690
// It is expected that those functions are all called _before_ the dockspace node submission.
17691
//-----------------------------------------------------------------------------
17692
// - DockBuilderDockWindow()
17693
// - DockBuilderGetNode()
17694
// - DockBuilderSetNodePos()
17695
// - DockBuilderSetNodeSize()
17696
// - DockBuilderAddNode()
17697
// - DockBuilderRemoveNode()
17698
// - DockBuilderRemoveNodeChildNodes()
17699
// - DockBuilderRemoveNodeDockedWindows()
17700
// - DockBuilderSplitNode()
17701
// - DockBuilderCopyNodeRec()
17702
// - DockBuilderCopyNode()
17703
// - DockBuilderCopyWindowSettings()
17704
// - DockBuilderCopyDockSpace()
17705
// - DockBuilderFinish()
17706
//-----------------------------------------------------------------------------
17707
17708
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
17709
0
{
17710
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
17711
0
    ImGuiID window_id = ImHashStr(window_name);
17712
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
17713
0
    {
17714
        // Apply to created window
17715
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
17716
0
        window->DockOrder = -1;
17717
0
    }
17718
0
    else
17719
0
    {
17720
        // Apply to settings
17721
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
17722
0
        if (settings == NULL)
17723
0
            settings = CreateNewWindowSettings(window_name);
17724
0
        settings->DockId = node_id;
17725
0
        settings->DockOrder = -1;
17726
0
    }
17727
0
}
17728
17729
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
17730
0
{
17731
0
    ImGuiContext* ctx = GImGui;
17732
0
    return DockContextFindNodeByID(ctx, node_id);
17733
0
}
17734
17735
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
17736
0
{
17737
0
    ImGuiContext* ctx = GImGui;
17738
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17739
0
    if (node == NULL)
17740
0
        return;
17741
0
    node->Pos = pos;
17742
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
17743
0
}
17744
17745
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
17746
0
{
17747
0
    ImGuiContext* ctx = GImGui;
17748
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17749
0
    if (node == NULL)
17750
0
        return;
17751
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17752
0
    node->Size = node->SizeRef = size;
17753
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17754
0
}
17755
17756
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
17757
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
17758
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
17759
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
17760
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
17761
// - Use (id == 0) to let the system allocate a node identifier.
17762
// - Existing node with a same id will be removed.
17763
ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags)
17764
0
{
17765
0
    ImGuiContext* ctx = GImGui;
17766
17767
0
    if (id != 0)
17768
0
        DockBuilderRemoveNode(id);
17769
17770
0
    ImGuiDockNode* node = NULL;
17771
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
17772
0
    {
17773
0
        DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
17774
0
        node = DockContextFindNodeByID(ctx, id);
17775
0
    }
17776
0
    else
17777
0
    {
17778
0
        node = DockContextAddNode(ctx, id);
17779
0
        node->SetLocalFlags(flags);
17780
0
    }
17781
0
    node->LastFrameAlive = ctx->FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
17782
0
    return node->ID;
17783
0
}
17784
17785
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
17786
0
{
17787
0
    ImGuiContext* ctx = GImGui;
17788
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17789
0
    if (node == NULL)
17790
0
        return;
17791
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
17792
0
    DockBuilderRemoveNodeChildNodes(node_id);
17793
    // Node may have moved or deleted if e.g. any merge happened
17794
0
    node = DockContextFindNodeByID(ctx, node_id);
17795
0
    if (node == NULL)
17796
0
        return;
17797
0
    if (node->IsCentralNode() && node->ParentNode)
17798
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17799
0
    DockContextRemoveNode(ctx, node, true);
17800
0
}
17801
17802
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
17803
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
17804
0
{
17805
0
    ImGuiContext* ctx = GImGui;
17806
0
    ImGuiDockContext* dc  = &ctx->DockContext;
17807
17808
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
17809
0
    if (root_id && root_node == NULL)
17810
0
        return;
17811
0
    bool has_central_node = false;
17812
17813
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
17814
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
17815
17816
    // Process active windows
17817
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
17818
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
17819
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17820
0
        {
17821
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
17822
0
            if (want_removal)
17823
0
            {
17824
0
                if (node->IsCentralNode())
17825
0
                    has_central_node = true;
17826
0
                if (root_id != 0)
17827
0
                    DockContextQueueNotifyRemovedNode(ctx, node);
17828
0
                if (root_node)
17829
0
                {
17830
0
                    DockNodeMoveWindows(root_node, node);
17831
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
17832
0
                }
17833
0
                nodes_to_remove.push_back(node);
17834
0
            }
17835
0
        }
17836
17837
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
17838
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
17839
0
    if (root_node)
17840
0
    {
17841
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
17842
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
17843
0
    }
17844
17845
    // Apply to settings
17846
0
    for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
17847
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
17848
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
17849
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
17850
0
                {
17851
0
                    settings->DockId = root_id;
17852
0
                    break;
17853
0
                }
17854
17855
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
17856
0
    if (nodes_to_remove.Size > 1)
17857
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
17858
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
17859
0
        DockContextRemoveNode(ctx, nodes_to_remove[n], false);
17860
17861
0
    if (root_id == 0)
17862
0
    {
17863
0
        dc->Nodes.Clear();
17864
0
        dc->Requests.clear();
17865
0
    }
17866
0
    else if (has_central_node)
17867
0
    {
17868
0
        root_node->CentralNode = root_node;
17869
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17870
0
    }
17871
0
}
17872
17873
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
17874
0
{
17875
    // Clear references in settings
17876
0
    ImGuiContext* ctx = GImGui;
17877
0
    ImGuiContext& g = *ctx;
17878
0
    if (clear_settings_refs)
17879
0
    {
17880
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
17881
0
        {
17882
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
17883
0
            if (!want_removal && settings->DockId != 0)
17884
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
17885
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
17886
0
                        want_removal = true;
17887
0
            if (want_removal)
17888
0
                settings->DockId = 0;
17889
0
        }
17890
0
    }
17891
17892
    // Clear references in windows
17893
0
    for (int n = 0; n < g.Windows.Size; n++)
17894
0
    {
17895
0
        ImGuiWindow* window = g.Windows[n];
17896
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
17897
0
        if (want_removal)
17898
0
        {
17899
0
            const ImGuiID backup_dock_id = window->DockId;
17900
0
            IM_UNUSED(backup_dock_id);
17901
0
            DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
17902
0
            if (!clear_settings_refs)
17903
0
                IM_ASSERT(window->DockId == backup_dock_id);
17904
0
        }
17905
0
    }
17906
0
}
17907
17908
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
17909
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
17910
// FIXME-DOCK: We are not exposing nor using split_outer.
17911
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
17912
0
{
17913
0
    ImGuiContext& g = *GImGui;
17914
0
    IM_ASSERT(split_dir != ImGuiDir_None);
17915
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
17916
17917
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
17918
0
    if (node == NULL)
17919
0
    {
17920
0
        IM_ASSERT(node != NULL);
17921
0
        return 0;
17922
0
    }
17923
17924
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
17925
17926
0
    ImGuiDockRequest req;
17927
0
    req.Type = ImGuiDockRequestType_Split;
17928
0
    req.DockTargetWindow = NULL;
17929
0
    req.DockTargetNode = node;
17930
0
    req.DockPayload = NULL;
17931
0
    req.DockSplitDir = split_dir;
17932
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
17933
0
    req.DockSplitOuter = false;
17934
0
    DockContextProcessDock(&g, &req);
17935
17936
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
17937
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
17938
0
    if (out_id_at_dir)
17939
0
        *out_id_at_dir = id_at_dir;
17940
0
    if (out_id_at_opposite_dir)
17941
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
17942
0
    return id_at_dir;
17943
0
}
17944
17945
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
17946
0
{
17947
0
    ImGuiContext& g = *GImGui;
17948
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
17949
0
    dst_node->SharedFlags = src_node->SharedFlags;
17950
0
    dst_node->LocalFlags = src_node->LocalFlags;
17951
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
17952
0
    dst_node->Pos = src_node->Pos;
17953
0
    dst_node->Size = src_node->Size;
17954
0
    dst_node->SizeRef = src_node->SizeRef;
17955
0
    dst_node->SplitAxis = src_node->SplitAxis;
17956
0
    dst_node->UpdateMergedFlags();
17957
17958
0
    out_node_remap_pairs->push_back(src_node->ID);
17959
0
    out_node_remap_pairs->push_back(dst_node->ID);
17960
17961
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
17962
0
        if (src_node->ChildNodes[child_n])
17963
0
        {
17964
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
17965
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
17966
0
        }
17967
17968
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
17969
0
    return dst_node;
17970
0
}
17971
17972
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
17973
0
{
17974
0
    ImGuiContext* ctx = GImGui;
17975
0
    IM_ASSERT(src_node_id != 0);
17976
0
    IM_ASSERT(dst_node_id != 0);
17977
0
    IM_ASSERT(out_node_remap_pairs != NULL);
17978
17979
0
    DockBuilderRemoveNode(dst_node_id);
17980
17981
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
17982
0
    IM_ASSERT(src_node != NULL);
17983
17984
0
    out_node_remap_pairs->clear();
17985
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
17986
17987
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
17988
0
}
17989
17990
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
17991
0
{
17992
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
17993
0
    if (src_window == NULL)
17994
0
        return;
17995
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
17996
0
    {
17997
0
        dst_window->Pos = src_window->Pos;
17998
0
        dst_window->Size = src_window->Size;
17999
0
        dst_window->SizeFull = src_window->SizeFull;
18000
0
        dst_window->Collapsed = src_window->Collapsed;
18001
0
    }
18002
0
    else
18003
0
    {
18004
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
18005
0
        if (!dst_settings)
18006
0
            dst_settings = CreateNewWindowSettings(dst_name);
18007
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
18008
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
18009
0
        {
18010
0
            dst_settings->ViewportPos = window_pos_2ih;
18011
0
            dst_settings->ViewportId = src_window->ViewportId;
18012
0
            dst_settings->Pos = ImVec2ih(0, 0);
18013
0
        }
18014
0
        else
18015
0
        {
18016
0
            dst_settings->Pos = window_pos_2ih;
18017
0
        }
18018
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
18019
0
        dst_settings->Collapsed = src_window->Collapsed;
18020
0
    }
18021
0
}
18022
18023
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
18024
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
18025
0
{
18026
0
    ImGuiContext& g = *GImGui;
18027
0
    IM_ASSERT(src_dockspace_id != 0);
18028
0
    IM_ASSERT(dst_dockspace_id != 0);
18029
0
    IM_ASSERT(in_window_remap_pairs != NULL);
18030
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
18031
18032
    // Duplicate entire dock
18033
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
18034
    // whereas we could attempt to at least keep them together in a new, same floating node.
18035
0
    ImVector<ImGuiID> node_remap_pairs;
18036
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
18037
18038
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
18039
    // (The windows associated to src_dockspace_id are staying in place)
18040
0
    ImVector<ImGuiID> src_windows;
18041
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
18042
0
    {
18043
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
18044
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
18045
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
18046
0
        src_windows.push_back(src_window_id);
18047
18048
        // Search in the remapping tables
18049
0
        ImGuiID src_dock_id = 0;
18050
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
18051
0
            src_dock_id = src_window->DockId;
18052
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
18053
0
            src_dock_id = src_window_settings->DockId;
18054
0
        ImGuiID dst_dock_id = 0;
18055
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18056
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
18057
0
            {
18058
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18059
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
18060
0
                break;
18061
0
            }
18062
18063
0
        if (dst_dock_id != 0)
18064
0
        {
18065
            // Docked windows gets redocked into the new node hierarchy.
18066
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
18067
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
18068
0
        }
18069
0
        else
18070
0
        {
18071
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
18072
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
18073
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
18074
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
18075
0
        }
18076
0
    }
18077
18078
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
18079
    // Find those windows and move to them to the cloned dock node. This may be optional?
18080
    // Dock those are a second step as undocking would invalidate source dock nodes.
18081
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
18082
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
18083
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18084
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
18085
0
        {
18086
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18087
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
18088
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18089
0
            {
18090
0
                ImGuiWindow* window = node->Windows[window_n];
18091
0
                if (src_windows.contains(window->ID))
18092
0
                    continue;
18093
18094
                // Docked windows gets redocked into the new node hierarchy.
18095
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
18096
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
18097
0
            }
18098
0
        }
18099
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
18100
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
18101
0
}
18102
18103
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
18104
void ImGui::DockBuilderFinish(ImGuiID root_id)
18105
0
{
18106
0
    ImGuiContext* ctx = GImGui;
18107
    //DockContextRebuild(ctx);
18108
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
18109
0
}
18110
18111
//-----------------------------------------------------------------------------
18112
// Docking: Begin/End Support Functions (called from Begin/End)
18113
//-----------------------------------------------------------------------------
18114
// - GetWindowAlwaysWantOwnTabBar()
18115
// - DockContextBindNodeToWindow()
18116
// - BeginDocked()
18117
// - BeginDockableDragDropSource()
18118
// - BeginDockableDragDropTarget()
18119
//-----------------------------------------------------------------------------
18120
18121
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
18122
440k
{
18123
440k
    ImGuiContext& g = *GImGui;
18124
440k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
18125
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18126
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18127
0
                return true;
18128
440k
    return false;
18129
440k
}
18130
18131
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18132
0
{
18133
0
    ImGuiContext& g = *ctx;
18134
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18135
0
    IM_ASSERT(window->DockNode == NULL);
18136
18137
    // We should not be docking into a split node (SetWindowDock should avoid this)
18138
0
    if (node && node->IsSplitNode())
18139
0
    {
18140
0
        DockContextProcessUndockWindow(ctx, window);
18141
0
        return NULL;
18142
0
    }
18143
18144
    // Create node
18145
0
    if (node == NULL)
18146
0
    {
18147
0
        node = DockContextAddNode(ctx, window->DockId);
18148
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18149
0
        node->LastFrameAlive = g.FrameCount;
18150
0
    }
18151
18152
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
18153
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
18154
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
18155
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
18156
0
    if (!node->IsVisible)
18157
0
    {
18158
0
        ImGuiDockNode* ancestor_node = node;
18159
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
18160
0
            ancestor_node = ancestor_node->ParentNode;
18161
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
18162
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
18163
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
18164
0
    }
18165
18166
    // Add window to node
18167
0
    bool node_was_visible = node->IsVisible;
18168
0
    DockNodeAddWindow(node, window, true);
18169
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
18170
0
    IM_ASSERT(node == window->DockNode);
18171
0
    return node;
18172
0
}
18173
18174
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
18175
0
{
18176
0
    ImGuiContext* ctx = GImGui;
18177
0
    ImGuiContext& g = *ctx;
18178
18179
    // Clear fields ahead so most early-out paths don't have to do it
18180
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
18181
18182
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
18183
0
    if (auto_dock_node)
18184
0
    {
18185
0
        if (window->DockId == 0)
18186
0
        {
18187
0
            IM_ASSERT(window->DockNode == NULL);
18188
0
            window->DockId = DockContextGenNodeID(ctx);
18189
0
        }
18190
0
    }
18191
0
    else
18192
0
    {
18193
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
18194
0
        bool want_undock = false;
18195
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
18196
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
18197
0
        if (want_undock)
18198
0
        {
18199
0
            DockContextProcessUndockWindow(ctx, window);
18200
0
            return;
18201
0
        }
18202
0
    }
18203
18204
    // Bind to our dock node
18205
0
    ImGuiDockNode* node = window->DockNode;
18206
0
    if (node != NULL)
18207
0
        IM_ASSERT(window->DockId == node->ID);
18208
0
    if (window->DockId != 0 && node == NULL)
18209
0
    {
18210
0
        node = DockContextBindNodeToWindow(ctx, window);
18211
0
        if (node == NULL)
18212
0
            return;
18213
0
    }
18214
18215
#if 0
18216
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
18217
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
18218
    {
18219
        DockContextProcessUndockWindow(ctx, window);
18220
        return;
18221
    }
18222
#endif
18223
18224
    // Undock if our dockspace node disappeared
18225
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
18226
0
    if (node->LastFrameAlive < g.FrameCount)
18227
0
    {
18228
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
18229
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
18230
0
        if (root_node->LastFrameAlive < g.FrameCount)
18231
0
            DockContextProcessUndockWindow(ctx, window);
18232
0
        else
18233
0
            window->DockIsActive = true;
18234
0
        return;
18235
0
    }
18236
18237
    // Store style overrides
18238
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18239
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18240
18241
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
18242
    // and never create neither a host window neither a tab bar.
18243
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
18244
0
    if (node->HostWindow == NULL)
18245
0
    {
18246
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
18247
0
            window->DockIsActive = true;
18248
0
        if (node->Windows.Size > 1)
18249
0
            DockNodeHideWindowDuringHostWindowCreation(window);
18250
0
        return;
18251
0
    }
18252
18253
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
18254
0
    IM_ASSERT(node->HostWindow);
18255
0
    IM_ASSERT(node->IsLeafNode());
18256
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
18257
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
18258
18259
    // Undock if we are submitted earlier than the host window
18260
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
18261
0
    {
18262
0
        DockContextProcessUndockWindow(ctx, window);
18263
0
        return;
18264
0
    }
18265
18266
    // Position/Size window
18267
0
    SetNextWindowPos(node->Pos);
18268
0
    SetNextWindowSize(node->Size);
18269
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
18270
0
    window->DockIsActive = true;
18271
0
    window->DockNodeIsVisible = true;
18272
0
    window->DockTabIsVisible = false;
18273
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
18274
0
        return;
18275
18276
    // When the window is selected we mark it as visible.
18277
0
    if (node->VisibleWindow == window)
18278
0
        window->DockTabIsVisible = true;
18279
18280
    // Update window flag
18281
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
18282
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
18283
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
18284
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
18285
0
    else
18286
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
18287
18288
    // Save new dock order only if the window has been visible once already
18289
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
18290
0
    if (node->TabBar && window->WasActive)
18291
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
18292
18293
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
18294
0
        *p_open = false;
18295
18296
    // Update ChildId to allow returning from Child to Parent with Escape
18297
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
18298
0
    window->ChildId = parent_window->GetID(window->Name);
18299
0
}
18300
18301
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
18302
185
{
18303
185
    ImGuiContext& g = *GImGui;
18304
185
    IM_ASSERT(g.ActiveId == window->MoveId);
18305
185
    IM_ASSERT(g.MovingWindow == window);
18306
185
    IM_ASSERT(g.CurrentWindow == window);
18307
18308
185
    g.LastItemData.ID = window->MoveId;
18309
185
    window = window->RootWindowDockTree;
18310
185
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18311
185
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
18312
185
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
18313
18
    {
18314
18
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
18315
18
        EndDragDropSource();
18316
18317
        // Store style overrides
18318
126
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18319
108
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18320
18
    }
18321
185
}
18322
18323
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
18324
27
{
18325
27
    ImGuiContext* ctx = GImGui;
18326
27
    ImGuiContext& g = *ctx;
18327
18328
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
18329
27
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18330
27
    if (!g.DragDropActive)
18331
0
        return;
18332
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
18333
27
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
18334
27
        return;
18335
18336
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
18337
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
18338
0
    const ImGuiPayload* payload = &g.DragDropPayload;
18339
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
18340
0
    {
18341
0
        EndDragDropTarget();
18342
0
        return;
18343
0
    }
18344
18345
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
18346
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
18347
0
    {
18348
        // Select target node
18349
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
18350
0
        bool dock_into_floating_window = false;
18351
0
        ImGuiDockNode* node = NULL;
18352
0
        if (window->DockNodeAsHost)
18353
0
        {
18354
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
18355
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
18356
18357
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
18358
            // In this case we need to fallback into any leaf mode, possibly the central node.
18359
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
18360
0
            if (node && node->IsDockSpace() && node->IsRootNode())
18361
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
18362
0
        }
18363
0
        else
18364
0
        {
18365
0
            if (window->DockNode)
18366
0
                node = window->DockNode;
18367
0
            else
18368
0
                dock_into_floating_window = true; // Dock into a regular window
18369
0
        }
18370
18371
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
18372
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
18373
18374
        // Preview docking request and find out split direction/ratio
18375
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
18376
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
18377
0
        if (do_preview && (node != NULL || dock_into_floating_window))
18378
0
        {
18379
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
18380
0
            ImGuiDockPreviewData split_inner;
18381
0
            ImGuiDockPreviewData split_outer;
18382
0
            ImGuiDockPreviewData* split_data = &split_inner;
18383
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
18384
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
18385
0
                {
18386
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
18387
0
                    if (split_outer.IsSplitDirExplicit)
18388
0
                        split_data = &split_outer;
18389
0
                }
18390
0
            if (!node || node->IsLeafNode())
18391
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
18392
0
            if (split_data == &split_outer)
18393
0
                split_inner.IsDropAllowed = false;
18394
18395
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
18396
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
18397
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
18398
18399
            // Queue docking request
18400
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
18401
0
                DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
18402
0
        }
18403
0
    }
18404
0
    EndDragDropTarget();
18405
0
}
18406
18407
//-----------------------------------------------------------------------------
18408
// Docking: Settings
18409
//-----------------------------------------------------------------------------
18410
// - DockSettingsRenameNodeReferences()
18411
// - DockSettingsRemoveNodeReferences()
18412
// - DockSettingsFindNodeSettings()
18413
// - DockSettingsHandler_ApplyAll()
18414
// - DockSettingsHandler_ReadOpen()
18415
// - DockSettingsHandler_ReadLine()
18416
// - DockSettingsHandler_DockNodeToSettings()
18417
// - DockSettingsHandler_WriteAll()
18418
//-----------------------------------------------------------------------------
18419
18420
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
18421
0
{
18422
0
    ImGuiContext& g = *GImGui;
18423
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
18424
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
18425
0
    {
18426
0
        ImGuiWindow* window = g.Windows[window_n];
18427
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
18428
0
            window->DockId = new_node_id;
18429
0
    }
18430
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18431
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18432
0
        if (settings->DockId == old_node_id)
18433
0
            settings->DockId = new_node_id;
18434
0
}
18435
18436
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
18437
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
18438
0
{
18439
0
    ImGuiContext& g = *GImGui;
18440
0
    int found = 0;
18441
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18442
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18443
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
18444
0
            if (settings->DockId == node_ids[node_n])
18445
0
            {
18446
0
                settings->DockId = 0;
18447
0
                settings->DockOrder = -1;
18448
0
                if (++found < node_ids_count)
18449
0
                    break;
18450
0
                return;
18451
0
            }
18452
0
}
18453
18454
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
18455
0
{
18456
    // FIXME-OPT
18457
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18458
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
18459
0
        if (dc->NodesSettings[n].ID == id)
18460
0
            return &dc->NodesSettings[n];
18461
0
    return NULL;
18462
0
}
18463
18464
// Clear settings data
18465
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18466
0
{
18467
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18468
0
    dc->NodesSettings.clear();
18469
0
    DockContextClearNodes(ctx, 0, true);
18470
0
}
18471
18472
// Recreate nodes based on settings data
18473
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18474
0
{
18475
    // Prune settings at boot time only
18476
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18477
0
    if (ctx->Windows.Size == 0)
18478
0
        DockContextPruneUnusedSettingsNodes(ctx);
18479
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
18480
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
18481
0
}
18482
18483
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
18484
0
{
18485
0
    if (strcmp(name, "Data") != 0)
18486
0
        return NULL;
18487
0
    return (void*)1;
18488
0
}
18489
18490
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
18491
0
{
18492
0
    char c = 0;
18493
0
    int x = 0, y = 0;
18494
0
    int r = 0;
18495
18496
    // Parsing, e.g.
18497
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
18498
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
18499
    // Important: this code expect currently fields in a fixed order.
18500
0
    ImGuiDockNodeSettings node;
18501
0
    line = ImStrSkipBlank(line);
18502
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
18503
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
18504
0
    else return;
18505
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
18506
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
18507
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
18508
0
    if (node.ParentNodeId == 0)
18509
0
    {
18510
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
18511
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
18512
0
    }
18513
0
    else
18514
0
    {
18515
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
18516
0
    }
18517
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
18518
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
18519
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
18520
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
18521
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
18522
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
18523
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
18524
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
18525
0
    if (node.ParentNodeId != 0)
18526
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
18527
0
            node.Depth = parent_settings->Depth + 1;
18528
0
    ctx->DockContext.NodesSettings.push_back(node);
18529
0
}
18530
18531
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
18532
0
{
18533
0
    ImGuiDockNodeSettings node_settings;
18534
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
18535
0
    node_settings.ID = node->ID;
18536
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
18537
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
18538
0
    node_settings.SelectedTabId = node->SelectedTabId;
18539
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
18540
0
    node_settings.Depth = (char)depth;
18541
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
18542
0
    node_settings.Pos = ImVec2ih(node->Pos);
18543
0
    node_settings.Size = ImVec2ih(node->Size);
18544
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
18545
0
    dc->NodesSettings.push_back(node_settings);
18546
0
    if (node->ChildNodes[0])
18547
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
18548
0
    if (node->ChildNodes[1])
18549
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
18550
0
}
18551
18552
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
18553
0
{
18554
0
    ImGuiContext& g = *ctx;
18555
0
    ImGuiDockContext* dc = &ctx->DockContext;
18556
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18557
0
        return;
18558
18559
    // Gather settings data
18560
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
18561
0
    dc->NodesSettings.resize(0);
18562
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
18563
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18564
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18565
0
            if (node->IsRootNode())
18566
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
18567
18568
0
    int max_depth = 0;
18569
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18570
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
18571
18572
    // Write to text buffer
18573
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
18574
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18575
0
    {
18576
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
18577
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
18578
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
18579
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
18580
0
        if (node_settings->ParentNodeId)
18581
0
        {
18582
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
18583
0
        }
18584
0
        else
18585
0
        {
18586
0
            if (node_settings->ParentWindowId)
18587
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
18588
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
18589
0
        }
18590
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
18591
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
18592
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
18593
0
            buf->appendf(" NoResize=1");
18594
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
18595
0
            buf->appendf(" CentralNode=1");
18596
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
18597
0
            buf->appendf(" NoTabBar=1");
18598
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
18599
0
            buf->appendf(" HiddenTabBar=1");
18600
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
18601
0
            buf->appendf(" NoWindowMenuButton=1");
18602
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
18603
0
            buf->appendf(" NoCloseButton=1");
18604
0
        if (node_settings->SelectedTabId)
18605
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
18606
18607
#if IMGUI_DEBUG_INI_SETTINGS
18608
        // [DEBUG] Include comments in the .ini file to ease debugging
18609
        if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
18610
        {
18611
            buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
18612
            if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
18613
                buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
18614
            // Iterate settings so we can give info about windows that didn't exist during the session.
18615
            int contains_window = 0;
18616
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18617
                if (settings->DockId == node_settings->ID)
18618
                {
18619
                    if (contains_window++ == 0)
18620
                        buf->appendf(" ; contains ");
18621
                    buf->appendf("'%s' ", settings->GetName());
18622
                }
18623
        }
18624
#endif
18625
0
        buf->appendf("\n");
18626
0
    }
18627
0
    buf->appendf("\n");
18628
0
}
18629
18630
18631
//-----------------------------------------------------------------------------
18632
// [SECTION] PLATFORM DEPENDENT HELPERS
18633
//-----------------------------------------------------------------------------
18634
18635
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
18636
18637
#ifdef _MSC_VER
18638
#pragma comment(lib, "user32")
18639
#pragma comment(lib, "kernel32")
18640
#endif
18641
18642
// Win32 clipboard implementation
18643
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
18644
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18645
{
18646
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18647
    g.ClipboardHandlerData.clear();
18648
    if (!::OpenClipboard(NULL))
18649
        return NULL;
18650
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
18651
    if (wbuf_handle == NULL)
18652
    {
18653
        ::CloseClipboard();
18654
        return NULL;
18655
    }
18656
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
18657
    {
18658
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
18659
        g.ClipboardHandlerData.resize(buf_len);
18660
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
18661
    }
18662
    ::GlobalUnlock(wbuf_handle);
18663
    ::CloseClipboard();
18664
    return g.ClipboardHandlerData.Data;
18665
}
18666
18667
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18668
{
18669
    if (!::OpenClipboard(NULL))
18670
        return;
18671
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
18672
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
18673
    if (wbuf_handle == NULL)
18674
    {
18675
        ::CloseClipboard();
18676
        return;
18677
    }
18678
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
18679
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
18680
    ::GlobalUnlock(wbuf_handle);
18681
    ::EmptyClipboard();
18682
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
18683
        ::GlobalFree(wbuf_handle);
18684
    ::CloseClipboard();
18685
}
18686
18687
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
18688
18689
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
18690
static PasteboardRef main_clipboard = 0;
18691
18692
// OSX clipboard implementation
18693
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
18694
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18695
{
18696
    if (!main_clipboard)
18697
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18698
    PasteboardClear(main_clipboard);
18699
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
18700
    if (cf_data)
18701
    {
18702
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
18703
        CFRelease(cf_data);
18704
    }
18705
}
18706
18707
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18708
{
18709
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18710
    if (!main_clipboard)
18711
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18712
    PasteboardSynchronize(main_clipboard);
18713
18714
    ItemCount item_count = 0;
18715
    PasteboardGetItemCount(main_clipboard, &item_count);
18716
    for (ItemCount i = 0; i < item_count; i++)
18717
    {
18718
        PasteboardItemID item_id = 0;
18719
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
18720
        CFArrayRef flavor_type_array = 0;
18721
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
18722
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
18723
        {
18724
            CFDataRef cf_data;
18725
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
18726
            {
18727
                g.ClipboardHandlerData.clear();
18728
                int length = (int)CFDataGetLength(cf_data);
18729
                g.ClipboardHandlerData.resize(length + 1);
18730
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
18731
                g.ClipboardHandlerData[length] = 0;
18732
                CFRelease(cf_data);
18733
                return g.ClipboardHandlerData.Data;
18734
            }
18735
        }
18736
    }
18737
    return NULL;
18738
}
18739
18740
#else
18741
18742
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
18743
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18744
0
{
18745
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18746
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
18747
0
}
18748
18749
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
18750
0
{
18751
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18752
0
    g.ClipboardHandlerData.clear();
18753
0
    const char* text_end = text + strlen(text);
18754
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
18755
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
18756
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
18757
0
}
18758
18759
#endif
18760
18761
// Win32 API IME support (for Asian languages, etc.)
18762
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
18763
18764
#include <imm.h>
18765
#ifdef _MSC_VER
18766
#pragma comment(lib, "imm32")
18767
#endif
18768
18769
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
18770
{
18771
    // Notify OS Input Method Editor of text input position
18772
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
18773
    if (hwnd == 0)
18774
        return;
18775
18776
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
18777
    if (HIMC himc = ::ImmGetContext(hwnd))
18778
    {
18779
        COMPOSITIONFORM composition_form = {};
18780
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18781
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18782
        composition_form.dwStyle = CFS_FORCE_POSITION;
18783
        ::ImmSetCompositionWindow(himc, &composition_form);
18784
        CANDIDATEFORM candidate_form = {};
18785
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
18786
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18787
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18788
        ::ImmSetCandidateWindow(himc, &candidate_form);
18789
        ::ImmReleaseContext(hwnd, himc);
18790
    }
18791
}
18792
18793
#else
18794
18795
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
18796
18797
#endif
18798
18799
//-----------------------------------------------------------------------------
18800
// [SECTION] METRICS/DEBUGGER WINDOW
18801
//-----------------------------------------------------------------------------
18802
// - RenderViewportThumbnail() [Internal]
18803
// - RenderViewportsThumbnails() [Internal]
18804
// - DebugTextEncoding()
18805
// - MetricsHelpMarker() [Internal]
18806
// - ShowFontAtlas() [Internal]
18807
// - ShowMetricsWindow()
18808
// - DebugNodeColumns() [Internal]
18809
// - DebugNodeDockNode() [Internal]
18810
// - DebugNodeDrawList() [Internal]
18811
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
18812
// - DebugNodeFont() [Internal]
18813
// - DebugNodeFontGlyph() [Internal]
18814
// - DebugNodeStorage() [Internal]
18815
// - DebugNodeTabBar() [Internal]
18816
// - DebugNodeViewport() [Internal]
18817
// - DebugNodeWindow() [Internal]
18818
// - DebugNodeWindowSettings() [Internal]
18819
// - DebugNodeWindowsList() [Internal]
18820
// - DebugNodeWindowsListByBeginStackParent() [Internal]
18821
//-----------------------------------------------------------------------------
18822
18823
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
18824
18825
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
18826
0
{
18827
0
    ImGuiContext& g = *GImGui;
18828
0
    ImGuiWindow* window = g.CurrentWindow;
18829
18830
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
18831
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
18832
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
18833
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
18834
0
    for (int i = 0; i != g.Windows.Size; i++)
18835
0
    {
18836
0
        ImGuiWindow* thumb_window = g.Windows[i];
18837
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
18838
0
            continue;
18839
0
        if (thumb_window->Viewport != viewport)
18840
0
            continue;
18841
18842
0
        ImRect thumb_r = thumb_window->Rect();
18843
0
        ImRect title_r = thumb_window->TitleBarRect();
18844
0
        thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off +  thumb_r.Max * scale));
18845
0
        title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
18846
0
        thumb_r.ClipWithFull(bb);
18847
0
        title_r.ClipWithFull(bb);
18848
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
18849
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
18850
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
18851
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18852
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
18853
0
    }
18854
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18855
0
}
18856
18857
static void RenderViewportsThumbnails()
18858
0
{
18859
0
    ImGuiContext& g = *GImGui;
18860
0
    ImGuiWindow* window = g.CurrentWindow;
18861
18862
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
18863
0
    float SCALE = 1.0f / 8.0f;
18864
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
18865
0
    for (int n = 0; n < g.Viewports.Size; n++)
18866
0
        bb_full.Add(g.Viewports[n]->GetMainRect());
18867
0
    ImVec2 p = window->DC.CursorPos;
18868
0
    ImVec2 off = p - bb_full.Min * SCALE;
18869
0
    for (int n = 0; n < g.Viewports.Size; n++)
18870
0
    {
18871
0
        ImGuiViewportP* viewport = g.Viewports[n];
18872
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
18873
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
18874
0
    }
18875
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
18876
0
}
18877
18878
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
18879
0
{
18880
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
18881
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
18882
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
18883
0
}
18884
18885
// Draw an arbitrary US keyboard layout to visualize translated keys
18886
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
18887
0
{
18888
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f);
18889
0
    const float  key_rounding = 3.0f;
18890
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);
18891
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);
18892
0
    const float  key_face_rounding = 2.0f;
18893
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);
18894
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
18895
0
    const float  key_row_offset = 9.0f;
18896
18897
0
    ImVec2 board_min = GetCursorScreenPos();
18898
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
18899
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
18900
18901
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
18902
0
    const KeyLayoutData keys_to_display[] =
18903
0
    {
18904
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
18905
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
18906
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
18907
0
    };
18908
18909
    // Elements rendered manually via ImDrawList API are not clipped automatically.
18910
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
18911
0
    Dummy(board_max - board_min);
18912
0
    if (!IsItemVisible())
18913
0
        return;
18914
0
    draw_list->PushClipRect(board_min, board_max, true);
18915
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
18916
0
    {
18917
0
        const KeyLayoutData* key_data = &keys_to_display[n];
18918
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
18919
0
        ImVec2 key_max = key_min + key_size;
18920
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
18921
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
18922
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
18923
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
18924
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
18925
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
18926
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
18927
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
18928
0
        if (ImGui::IsKeyDown(key_data->Key))
18929
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
18930
0
    }
18931
0
    draw_list->PopClipRect();
18932
0
}
18933
18934
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
18935
void ImGui::DebugTextEncoding(const char* str)
18936
0
{
18937
0
    Text("Text: \"%s\"", str);
18938
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
18939
0
        return;
18940
0
    TableSetupColumn("Offset");
18941
0
    TableSetupColumn("UTF-8");
18942
0
    TableSetupColumn("Glyph");
18943
0
    TableSetupColumn("Codepoint");
18944
0
    TableHeadersRow();
18945
0
    for (const char* p = str; *p != 0; )
18946
0
    {
18947
0
        unsigned int c;
18948
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
18949
0
        TableNextColumn();
18950
0
        Text("%d", (int)(p - str));
18951
0
        TableNextColumn();
18952
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
18953
0
        {
18954
0
            if (byte_index > 0)
18955
0
                SameLine();
18956
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
18957
0
        }
18958
0
        TableNextColumn();
18959
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
18960
0
            TextUnformatted(p, p + c_utf8_len);
18961
0
        else
18962
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
18963
0
        TableNextColumn();
18964
0
        Text("U+%04X", (int)c);
18965
0
        p += c_utf8_len;
18966
0
    }
18967
0
    EndTable();
18968
0
}
18969
18970
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
18971
static void MetricsHelpMarker(const char* desc)
18972
0
{
18973
0
    ImGui::TextDisabled("(?)");
18974
0
    if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort) && ImGui::BeginTooltip())
18975
0
    {
18976
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
18977
0
        ImGui::TextUnformatted(desc);
18978
0
        ImGui::PopTextWrapPos();
18979
0
        ImGui::EndTooltip();
18980
0
    }
18981
0
}
18982
18983
// [DEBUG] List fonts in a font atlas and display its texture
18984
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
18985
0
{
18986
0
    for (int i = 0; i < atlas->Fonts.Size; i++)
18987
0
    {
18988
0
        ImFont* font = atlas->Fonts[i];
18989
0
        PushID(font);
18990
0
        DebugNodeFont(font);
18991
0
        PopID();
18992
0
    }
18993
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
18994
0
    {
18995
0
        ImGuiContext& g = *GImGui;
18996
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
18997
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
18998
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
18999
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
19000
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
19001
0
        TreePop();
19002
0
    }
19003
0
}
19004
19005
void ImGui::ShowMetricsWindow(bool* p_open)
19006
0
{
19007
0
    ImGuiContext& g = *GImGui;
19008
0
    ImGuiIO& io = g.IO;
19009
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19010
0
    if (cfg->ShowDebugLog)
19011
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
19012
0
    if (cfg->ShowStackTool)
19013
0
        ShowStackToolWindow(&cfg->ShowStackTool);
19014
19015
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
19016
0
    {
19017
0
        End();
19018
0
        return;
19019
0
    }
19020
19021
    // Basic info
19022
0
    Text("Dear ImGui %s", GetVersion());
19023
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
19024
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
19025
0
    Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations);
19026
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
19027
19028
0
    Separator();
19029
19030
    // Debugging enums
19031
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
19032
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
19033
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
19034
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
19035
0
    if (cfg->ShowWindowsRectsType < 0)
19036
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
19037
0
    if (cfg->ShowTablesRectsType < 0)
19038
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
19039
19040
0
    struct Funcs
19041
0
    {
19042
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
19043
0
        {
19044
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
19045
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
19046
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
19047
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
19048
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
19049
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
19050
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
19051
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
19052
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
19053
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
19054
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); } // Note: y1/y2 not always accurate
19055
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
19056
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
19057
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
19058
0
            IM_ASSERT(0);
19059
0
            return ImRect();
19060
0
        }
19061
19062
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
19063
0
        {
19064
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
19065
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
19066
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
19067
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
19068
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
19069
0
            else if (rect_type == WRT_Content)       { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
19070
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
19071
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
19072
0
            IM_ASSERT(0);
19073
0
            return ImRect();
19074
0
        }
19075
0
    };
19076
19077
    // Tools
19078
0
    if (TreeNode("Tools"))
19079
0
    {
19080
0
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
19081
0
        SameLine();
19082
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
19083
0
        if (show_encoding_viewer)
19084
0
        {
19085
0
            static char buf[100] = "";
19086
0
            SetNextItemWidth(-FLT_MIN);
19087
0
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
19088
0
            if (buf[0] != 0)
19089
0
                DebugTextEncoding(buf);
19090
0
            TreePop();
19091
0
        }
19092
19093
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
19094
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
19095
0
            DebugStartItemPicker();
19096
0
        SameLine();
19097
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
19098
19099
        // Stack Tool is your best friend!
19100
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
19101
0
        SameLine();
19102
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
19103
19104
        // Stack Tool is your best friend!
19105
0
        Checkbox("Show Stack Tool", &cfg->ShowStackTool);
19106
0
        SameLine();
19107
0
        MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code.");
19108
19109
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
19110
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
19111
0
        SameLine();
19112
0
        SetNextItemWidth(GetFontSize() * 12);
19113
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
19114
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
19115
0
        {
19116
0
            BulletText("'%s':", g.NavWindow->Name);
19117
0
            Indent();
19118
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
19119
0
            {
19120
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
19121
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
19122
0
            }
19123
0
            Unindent();
19124
0
        }
19125
19126
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
19127
0
        SameLine();
19128
0
        SetNextItemWidth(GetFontSize() * 12);
19129
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
19130
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
19131
0
        {
19132
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19133
0
            {
19134
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19135
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
19136
0
                    continue;
19137
19138
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
19139
0
                if (IsItemHovered())
19140
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19141
0
                Indent();
19142
0
                char buf[128];
19143
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
19144
0
                {
19145
0
                    if (rect_n >= TRT_ColumnsRect)
19146
0
                    {
19147
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
19148
0
                            continue;
19149
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19150
0
                        {
19151
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
19152
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
19153
0
                            Selectable(buf);
19154
0
                            if (IsItemHovered())
19155
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19156
0
                        }
19157
0
                    }
19158
0
                    else
19159
0
                    {
19160
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
19161
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
19162
0
                        Selectable(buf);
19163
0
                        if (IsItemHovered())
19164
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19165
0
                    }
19166
0
                }
19167
0
                Unindent();
19168
0
            }
19169
0
        }
19170
19171
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
19172
0
        SameLine();
19173
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
19174
19175
0
        TreePop();
19176
0
    }
19177
19178
    // Windows
19179
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
19180
0
    {
19181
        //SetNextItemOpen(true, ImGuiCond_Once);
19182
0
        DebugNodeWindowsList(&g.Windows, "By display order");
19183
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
19184
0
        if (TreeNode("By submission order (begin stack)"))
19185
0
        {
19186
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
19187
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
19188
0
            temp_buffer.resize(0);
19189
0
            for (int i = 0; i < g.Windows.Size; i++)
19190
0
                if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount)
19191
0
                    temp_buffer.push_back(g.Windows[i]);
19192
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
19193
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
19194
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
19195
0
            TreePop();
19196
0
        }
19197
19198
0
        TreePop();
19199
0
    }
19200
19201
    // DrawLists
19202
0
    int drawlist_count = 0;
19203
0
    for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
19204
0
        drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
19205
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
19206
0
    {
19207
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
19208
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
19209
0
        for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
19210
0
        {
19211
0
            ImGuiViewportP* viewport = g.Viewports[viewport_i];
19212
0
            bool viewport_has_drawlist = false;
19213
0
            for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
19214
0
                for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
19215
0
                {
19216
0
                    if (!viewport_has_drawlist)
19217
0
                        Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
19218
0
                    viewport_has_drawlist = true;
19219
0
                    DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
19220
0
                }
19221
0
        }
19222
0
        TreePop();
19223
0
    }
19224
19225
    // Viewports
19226
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
19227
0
    {
19228
0
        Indent(GetTreeNodeToLabelSpacing());
19229
0
        RenderViewportsThumbnails();
19230
0
        Unindent(GetTreeNodeToLabelSpacing());
19231
19232
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
19233
0
        SameLine();
19234
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
19235
0
        if (open)
19236
0
        {
19237
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
19238
0
            {
19239
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
19240
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
19241
0
                    i, mon.DpiScale * 100.0f,
19242
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
19243
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
19244
0
            }
19245
0
            TreePop();
19246
0
        }
19247
19248
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19249
0
        if (TreeNode("Inferred Z order (front-to-back)"))
19250
0
        {
19251
0
            static ImVector<ImGuiViewportP*> viewports;
19252
0
            viewports.resize(g.Viewports.Size);
19253
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
19254
0
            if (viewports.Size > 1)
19255
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
19256
0
            for (ImGuiViewportP* viewport : viewports)
19257
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
19258
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
19259
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
19260
0
                    viewport->Window ? viewport->Window->Name : "N/A");
19261
0
            TreePop();
19262
0
        }
19263
0
        for (int i = 0; i < g.Viewports.Size; i++)
19264
0
            DebugNodeViewport(g.Viewports[i]);
19265
0
        TreePop();
19266
0
    }
19267
19268
    // Details for Popups
19269
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
19270
0
    {
19271
0
        for (int i = 0; i < g.OpenPopupStack.Size; i++)
19272
0
        {
19273
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
19274
0
            const ImGuiPopupData* popup_data = &g.OpenPopupStack[i];
19275
0
            ImGuiWindow* window = popup_data->Window;
19276
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
19277
0
                popup_data->PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
19278
0
                popup_data->BackupNavWindow ? popup_data->BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
19279
0
        }
19280
0
        TreePop();
19281
0
    }
19282
19283
    // Details for TabBars
19284
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
19285
0
    {
19286
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
19287
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
19288
0
            {
19289
0
                PushID(tab_bar);
19290
0
                DebugNodeTabBar(tab_bar, "TabBar");
19291
0
                PopID();
19292
0
            }
19293
0
        TreePop();
19294
0
    }
19295
19296
    // Details for Tables
19297
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
19298
0
    {
19299
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
19300
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
19301
0
                DebugNodeTable(table);
19302
0
        TreePop();
19303
0
    }
19304
19305
    // Details for Fonts
19306
0
    ImFontAtlas* atlas = g.IO.Fonts;
19307
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
19308
0
    {
19309
0
        ShowFontAtlas(atlas);
19310
0
        TreePop();
19311
0
    }
19312
19313
    // Details for InputText
19314
0
    if (TreeNode("InputText"))
19315
0
    {
19316
0
        DebugNodeInputTextState(&g.InputTextState);
19317
0
        TreePop();
19318
0
    }
19319
19320
    // Details for Docking
19321
0
#ifdef IMGUI_HAS_DOCK
19322
0
    if (TreeNode("Docking"))
19323
0
    {
19324
0
        static bool root_nodes_only = true;
19325
0
        ImGuiDockContext* dc = &g.DockContext;
19326
0
        Checkbox("List root nodes", &root_nodes_only);
19327
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
19328
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
19329
0
        SameLine();
19330
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
19331
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
19332
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19333
0
                if (!root_nodes_only || node->IsRootNode())
19334
0
                    DebugNodeDockNode(node, "Node");
19335
0
        TreePop();
19336
0
    }
19337
0
#endif // #ifdef IMGUI_HAS_DOCK
19338
19339
    // Settings
19340
0
    if (TreeNode("Settings"))
19341
0
    {
19342
0
        if (SmallButton("Clear"))
19343
0
            ClearIniSettings();
19344
0
        SameLine();
19345
0
        if (SmallButton("Save to memory"))
19346
0
            SaveIniSettingsToMemory();
19347
0
        SameLine();
19348
0
        if (SmallButton("Save to disk"))
19349
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
19350
0
        SameLine();
19351
0
        if (g.IO.IniFilename)
19352
0
            Text("\"%s\"", g.IO.IniFilename);
19353
0
        else
19354
0
            TextUnformatted("<NULL>");
19355
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
19356
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
19357
0
        {
19358
0
            for (int n = 0; n < g.SettingsHandlers.Size; n++)
19359
0
                BulletText("%s", g.SettingsHandlers[n].TypeName);
19360
0
            TreePop();
19361
0
        }
19362
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
19363
0
        {
19364
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19365
0
                DebugNodeWindowSettings(settings);
19366
0
            TreePop();
19367
0
        }
19368
19369
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
19370
0
        {
19371
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
19372
0
                DebugNodeTableSettings(settings);
19373
0
            TreePop();
19374
0
        }
19375
19376
0
#ifdef IMGUI_HAS_DOCK
19377
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
19378
0
        {
19379
0
            ImGuiDockContext* dc = &g.DockContext;
19380
0
            Text("In SettingsWindows:");
19381
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19382
0
                if (settings->DockId != 0)
19383
0
                    BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId);
19384
0
            Text("In SettingsNodes:");
19385
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
19386
0
            {
19387
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
19388
0
                const char* selected_tab_name = NULL;
19389
0
                if (settings->SelectedTabId)
19390
0
                {
19391
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
19392
0
                        selected_tab_name = window->Name;
19393
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
19394
0
                        selected_tab_name = window_settings->GetName();
19395
0
                }
19396
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
19397
0
            }
19398
0
            TreePop();
19399
0
        }
19400
0
#endif // #ifdef IMGUI_HAS_DOCK
19401
19402
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
19403
0
        {
19404
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
19405
0
            TreePop();
19406
0
        }
19407
0
        TreePop();
19408
0
    }
19409
19410
0
    if (TreeNode("Inputs"))
19411
0
    {
19412
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
19413
0
        {
19414
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
19415
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
19416
0
            Indent();
19417
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
19418
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
19419
#else
19420
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
19421
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
19422
#endif
19423
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
19424
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19425
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19426
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
19427
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
19428
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
19429
0
            Unindent();
19430
0
        }
19431
19432
0
        Text("MOUSE STATE");
19433
0
        {
19434
0
            Indent();
19435
0
            if (IsMousePosValid())
19436
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
19437
0
            else
19438
0
                Text("Mouse pos: <INVALID>");
19439
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
19440
0
            int count = IM_ARRAYSIZE(io.MouseDown);
19441
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
19442
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
19443
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
19444
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
19445
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
19446
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
19447
0
            Unindent();
19448
0
        }
19449
19450
0
        Text("MOUSE WHEELING");
19451
0
        {
19452
0
            Indent();
19453
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
19454
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
19455
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
19456
0
            Unindent();
19457
0
        }
19458
19459
0
        Text("KEY OWNERS");
19460
0
        {
19461
0
            Indent();
19462
0
            if (BeginListBox("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19463
0
            {
19464
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19465
0
                {
19466
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
19467
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
19468
0
                        continue;
19469
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
19470
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
19471
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
19472
0
                }
19473
0
                EndListBox();
19474
0
            }
19475
0
            Unindent();
19476
0
        }
19477
0
        Text("SHORTCUT ROUTING");
19478
0
        {
19479
0
            Indent();
19480
0
            if (BeginListBox("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19481
0
            {
19482
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19483
0
                {
19484
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
19485
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
19486
0
                    {
19487
0
                        char key_chord_name[64];
19488
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
19489
0
                        GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
19490
0
                        Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
19491
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
19492
0
                        idx = routing_data->NextEntryIndex;
19493
0
                    }
19494
0
                }
19495
0
                EndListBox();
19496
0
            }
19497
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19498
0
            Unindent();
19499
0
        }
19500
0
        TreePop();
19501
0
    }
19502
19503
0
    if (TreeNode("Internal state"))
19504
0
    {
19505
0
        Text("WINDOWING");
19506
0
        Indent();
19507
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
19508
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
19509
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
19510
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
19511
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
19512
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19513
0
        Unindent();
19514
19515
0
        Text("ITEMS");
19516
0
        Indent();
19517
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
19518
0
        DebugLocateItemOnHover(g.ActiveId);
19519
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
19520
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19521
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
19522
0
        Text("HoverDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverDelayId, g.HoverDelayTimer, g.HoverDelayClearTimer);
19523
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
19524
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
19525
0
        Unindent();
19526
19527
0
        Text("NAV,FOCUS");
19528
0
        Indent();
19529
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
19530
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
19531
0
        DebugLocateItemOnHover(g.NavId);
19532
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
19533
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
19534
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
19535
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
19536
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
19537
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
19538
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
19539
0
        Unindent();
19540
19541
0
        TreePop();
19542
0
    }
19543
19544
    // Overlay: Display windows Rectangles and Begin Order
19545
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
19546
0
    {
19547
0
        for (int n = 0; n < g.Windows.Size; n++)
19548
0
        {
19549
0
            ImGuiWindow* window = g.Windows[n];
19550
0
            if (!window->WasActive)
19551
0
                continue;
19552
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
19553
0
            if (cfg->ShowWindowsRects)
19554
0
            {
19555
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
19556
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19557
0
            }
19558
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
19559
0
            {
19560
0
                char buf[32];
19561
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
19562
0
                float font_size = GetFontSize();
19563
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
19564
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
19565
0
            }
19566
0
        }
19567
0
    }
19568
19569
    // Overlay: Display Tables Rectangles
19570
0
    if (cfg->ShowTablesRects)
19571
0
    {
19572
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19573
0
        {
19574
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19575
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
19576
0
                continue;
19577
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
19578
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
19579
0
            {
19580
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19581
0
                {
19582
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
19583
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
19584
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
19585
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
19586
0
                }
19587
0
            }
19588
0
            else
19589
0
            {
19590
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
19591
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19592
0
            }
19593
0
        }
19594
0
    }
19595
19596
0
#ifdef IMGUI_HAS_DOCK
19597
    // Overlay: Display Docking info
19598
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
19599
0
    {
19600
0
        char buf[64] = "";
19601
0
        char* p = buf;
19602
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
19603
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19604
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
19605
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
19606
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
19607
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
19608
0
        int depth = DockNodeGetDepth(node);
19609
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
19610
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
19611
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
19612
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
19613
0
    }
19614
0
#endif // #ifdef IMGUI_HAS_DOCK
19615
19616
0
    End();
19617
0
}
19618
19619
// [DEBUG] Display contents of Columns
19620
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
19621
0
{
19622
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
19623
0
        return;
19624
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
19625
0
    for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
19626
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
19627
0
    TreePop();
19628
0
}
19629
19630
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
19631
0
{
19632
0
    using namespace ImGui;
19633
0
    PushID(label);
19634
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
19635
0
    Text("%s:", label);
19636
0
    if (!enabled)
19637
0
        BeginDisabled();
19638
0
    CheckboxFlags("NoSplit", p_flags, ImGuiDockNodeFlags_NoSplit);
19639
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
19640
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
19641
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
19642
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
19643
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
19644
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
19645
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
19646
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking);
19647
0
    CheckboxFlags("NoDockingSplitMe", p_flags, ImGuiDockNodeFlags_NoDockingSplitMe);
19648
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
19649
0
    CheckboxFlags("NoDockingOverMe", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
19650
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
19651
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
19652
0
    if (!enabled)
19653
0
        EndDisabled();
19654
0
    PopStyleVar();
19655
0
    PopID();
19656
0
}
19657
19658
// [DEBUG] Display contents of ImDockNode
19659
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
19660
0
{
19661
0
    ImGuiContext& g = *GImGui;
19662
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
19663
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
19664
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19665
0
    bool open;
19666
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19667
0
    if (node->Windows.Size > 0)
19668
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19669
0
    else
19670
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19671
0
    if (!is_alive) { PopStyleColor(); }
19672
0
    if (is_active && IsItemHovered())
19673
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
19674
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
19675
0
    if (open)
19676
0
    {
19677
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
19678
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
19679
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
19680
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
19681
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
19682
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
19683
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
19684
0
        BulletText("Misc:%s%s%s%s%s%s%s",
19685
0
            node->IsDockSpace() ? " IsDockSpace" : "",
19686
0
            node->IsCentralNode() ? " IsCentralNode" : "",
19687
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
19688
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
19689
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
19690
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
19691
0
        {
19692
0
            if (BeginTable("flags", 4))
19693
0
            {
19694
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
19695
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
19696
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
19697
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
19698
0
                EndTable();
19699
0
            }
19700
0
            TreePop();
19701
0
        }
19702
0
        if (node->ParentNode)
19703
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
19704
0
        if (node->ChildNodes[0])
19705
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
19706
0
        if (node->ChildNodes[1])
19707
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
19708
0
        if (node->TabBar)
19709
0
            DebugNodeTabBar(node->TabBar, "TabBar");
19710
0
        DebugNodeWindowsList(&node->Windows, "Windows");
19711
19712
0
        TreePop();
19713
0
    }
19714
0
}
19715
19716
// [DEBUG] Display contents of ImDrawList
19717
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
19718
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
19719
0
{
19720
0
    ImGuiContext& g = *GImGui;
19721
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19722
0
    int cmd_count = draw_list->CmdBuffer.Size;
19723
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
19724
0
        cmd_count--;
19725
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
19726
0
    if (draw_list == GetWindowDrawList())
19727
0
    {
19728
0
        SameLine();
19729
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
19730
0
        if (node_open)
19731
0
            TreePop();
19732
0
        return;
19733
0
    }
19734
19735
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
19736
0
    if (window && IsItemHovered() && fg_draw_list)
19737
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19738
0
    if (!node_open)
19739
0
        return;
19740
19741
0
    if (window && !window->WasActive)
19742
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
19743
19744
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
19745
0
    {
19746
0
        if (pcmd->UserCallback)
19747
0
        {
19748
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
19749
0
            continue;
19750
0
        }
19751
19752
0
        char buf[300];
19753
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
19754
0
            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
19755
0
            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
19756
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
19757
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
19758
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
19759
0
        if (!pcmd_node_open)
19760
0
            continue;
19761
19762
        // Calculate approximate coverage area (touched pixel count)
19763
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
19764
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
19765
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
19766
0
        float total_area = 0.0f;
19767
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
19768
0
        {
19769
0
            ImVec2 triangle[3];
19770
0
            for (int n = 0; n < 3; n++, idx_n++)
19771
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
19772
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
19773
0
        }
19774
19775
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
19776
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
19777
0
        Selectable(buf);
19778
0
        if (IsItemHovered() && fg_draw_list)
19779
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
19780
19781
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
19782
0
        ImGuiListClipper clipper;
19783
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
19784
0
        while (clipper.Step())
19785
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
19786
0
            {
19787
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
19788
0
                ImVec2 triangle[3];
19789
0
                for (int n = 0; n < 3; n++, idx_i++)
19790
0
                {
19791
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
19792
0
                    triangle[n] = v.pos;
19793
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
19794
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
19795
0
                }
19796
19797
0
                Selectable(buf, false);
19798
0
                if (fg_draw_list && IsItemHovered())
19799
0
                {
19800
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
19801
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19802
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
19803
0
                    fg_draw_list->Flags = backup_flags;
19804
0
                }
19805
0
            }
19806
0
        TreePop();
19807
0
    }
19808
0
    TreePop();
19809
0
}
19810
19811
// [DEBUG] Display mesh/aabb of a ImDrawCmd
19812
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
19813
0
{
19814
0
    IM_ASSERT(show_mesh || show_aabb);
19815
19816
    // Draw wire-frame version of all triangles
19817
0
    ImRect clip_rect = draw_cmd->ClipRect;
19818
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19819
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
19820
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19821
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
19822
0
    {
19823
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
19824
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
19825
19826
0
        ImVec2 triangle[3];
19827
0
        for (int n = 0; n < 3; n++, idx_n++)
19828
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
19829
0
        if (show_mesh)
19830
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
19831
0
    }
19832
    // Draw bounding boxes
19833
0
    if (show_aabb)
19834
0
    {
19835
0
        out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
19836
0
        out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
19837
0
    }
19838
0
    out_draw_list->Flags = backup_flags;
19839
0
}
19840
19841
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
19842
void ImGui::DebugNodeFont(ImFont* font)
19843
0
{
19844
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
19845
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
19846
0
    SameLine();
19847
0
    if (SmallButton("Set as default"))
19848
0
        GetIO().FontDefault = font;
19849
0
    if (!opened)
19850
0
        return;
19851
19852
    // Display preview text
19853
0
    PushFont(font);
19854
0
    Text("The quick brown fox jumps over the lazy dog");
19855
0
    PopFont();
19856
19857
    // Display details
19858
0
    SetNextItemWidth(GetFontSize() * 8);
19859
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
19860
0
    SameLine(); MetricsHelpMarker(
19861
0
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
19862
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
19863
0
        "You may oversample them to get some flexibility with scaling. "
19864
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
19865
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
19866
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
19867
0
    char c_str[5];
19868
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
19869
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
19870
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
19871
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
19872
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
19873
0
        if (font->ConfigData)
19874
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
19875
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
19876
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
19877
19878
    // Display all glyphs of the fonts in separate pages of 256 characters
19879
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
19880
0
    {
19881
0
        ImDrawList* draw_list = GetWindowDrawList();
19882
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
19883
0
        const float cell_size = font->FontSize * 1;
19884
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
19885
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
19886
0
        {
19887
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
19888
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
19889
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
19890
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
19891
0
            {
19892
0
                base += 4096 - 256;
19893
0
                continue;
19894
0
            }
19895
19896
0
            int count = 0;
19897
0
            for (unsigned int n = 0; n < 256; n++)
19898
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
19899
0
                    count++;
19900
0
            if (count <= 0)
19901
0
                continue;
19902
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
19903
0
                continue;
19904
19905
            // Draw a 16x16 grid of glyphs
19906
0
            ImVec2 base_pos = GetCursorScreenPos();
19907
0
            for (unsigned int n = 0; n < 256; n++)
19908
0
            {
19909
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
19910
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
19911
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
19912
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
19913
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
19914
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
19915
0
                if (!glyph)
19916
0
                    continue;
19917
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
19918
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
19919
0
                {
19920
0
                    DebugNodeFontGlyph(font, glyph);
19921
0
                    EndTooltip();
19922
0
                }
19923
0
            }
19924
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
19925
0
            TreePop();
19926
0
        }
19927
0
        TreePop();
19928
0
    }
19929
0
    TreePop();
19930
0
}
19931
19932
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
19933
0
{
19934
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
19935
0
    Separator();
19936
0
    Text("Visible: %d", glyph->Visible);
19937
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
19938
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
19939
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
19940
0
}
19941
19942
// [DEBUG] Display contents of ImGuiStorage
19943
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
19944
0
{
19945
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
19946
0
        return;
19947
0
    for (int n = 0; n < storage->Data.Size; n++)
19948
0
    {
19949
0
        const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
19950
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
19951
0
    }
19952
0
    TreePop();
19953
0
}
19954
19955
// [DEBUG] Display contents of ImGuiTabBar
19956
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
19957
0
{
19958
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
19959
0
    char buf[256];
19960
0
    char* p = buf;
19961
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
19962
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
19963
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
19964
0
    p += ImFormatString(p, buf_end - p, "  { ");
19965
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
19966
0
    {
19967
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19968
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
19969
0
    }
19970
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
19971
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19972
0
    bool open = TreeNode(label, "%s", buf);
19973
0
    if (!is_active) { PopStyleColor(); }
19974
0
    if (is_active && IsItemHovered())
19975
0
    {
19976
0
        ImDrawList* draw_list = GetForegroundDrawList();
19977
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
19978
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19979
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19980
0
    }
19981
0
    if (open)
19982
0
    {
19983
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
19984
0
        {
19985
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19986
0
            PushID(tab);
19987
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
19988
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
19989
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
19990
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
19991
0
            PopID();
19992
0
        }
19993
0
        TreePop();
19994
0
    }
19995
0
}
19996
19997
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
19998
0
{
19999
0
    SetNextItemOpen(true, ImGuiCond_Once);
20000
0
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
20001
0
    {
20002
0
        ImGuiWindowFlags flags = viewport->Flags;
20003
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
20004
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
20005
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
20006
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
20007
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
20008
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
20009
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
20010
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
20011
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
20012
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
20013
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
20014
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
20015
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
20016
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
20017
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
20018
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
20019
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
20020
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
20021
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
20022
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
20023
0
        for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
20024
0
            for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
20025
0
                DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
20026
0
        TreePop();
20027
0
    }
20028
0
}
20029
20030
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
20031
0
{
20032
0
    if (window == NULL)
20033
0
    {
20034
0
        BulletText("%s: NULL", label);
20035
0
        return;
20036
0
    }
20037
20038
0
    ImGuiContext& g = *GImGui;
20039
0
    const bool is_active = window->WasActive;
20040
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20041
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20042
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
20043
0
    if (!is_active) { PopStyleColor(); }
20044
0
    if (IsItemHovered() && is_active)
20045
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20046
0
    if (!open)
20047
0
        return;
20048
20049
0
    if (window->MemoryCompacted)
20050
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
20051
20052
0
    ImGuiWindowFlags flags = window->Flags;
20053
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
20054
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
20055
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
20056
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
20057
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
20058
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
20059
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
20060
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
20061
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
20062
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
20063
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20064
0
    {
20065
0
        ImRect r = window->NavRectRel[layer];
20066
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
20067
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
20068
0
        else
20069
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
20070
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
20071
0
    }
20072
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
20073
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20074
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
20075
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
20076
20077
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
20078
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
20079
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
20080
0
    if (window->DockNode || window->DockNodeAsHost)
20081
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
20082
20083
0
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
20084
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
20085
0
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
20086
0
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
20087
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
20088
0
    {
20089
0
        for (int n = 0; n < window->ColumnsStorage.Size; n++)
20090
0
            DebugNodeColumns(&window->ColumnsStorage[n]);
20091
0
        TreePop();
20092
0
    }
20093
0
    DebugNodeStorage(&window->StateStorage, "Storage");
20094
0
    TreePop();
20095
0
}
20096
20097
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
20098
0
{
20099
0
    if (settings->WantDelete)
20100
0
        BeginDisabled();
20101
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
20102
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
20103
0
    if (settings->WantDelete)
20104
0
        EndDisabled();
20105
0
}
20106
20107
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
20108
0
{
20109
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
20110
0
        return;
20111
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
20112
0
    {
20113
0
        PushID((*windows)[i]);
20114
0
        DebugNodeWindow((*windows)[i], "Window");
20115
0
        PopID();
20116
0
    }
20117
0
    TreePop();
20118
0
}
20119
20120
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
20121
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
20122
0
{
20123
0
    for (int i = 0; i < windows_size; i++)
20124
0
    {
20125
0
        ImGuiWindow* window = windows[i];
20126
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
20127
0
            continue;
20128
0
        char buf[20];
20129
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
20130
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
20131
0
        DebugNodeWindow(window, buf);
20132
0
        Indent();
20133
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
20134
0
        Unindent();
20135
0
    }
20136
0
}
20137
20138
//-----------------------------------------------------------------------------
20139
// [SECTION] DEBUG LOG WINDOW
20140
//-----------------------------------------------------------------------------
20141
20142
void ImGui::DebugLog(const char* fmt, ...)
20143
0
{
20144
0
    va_list args;
20145
0
    va_start(args, fmt);
20146
0
    DebugLogV(fmt, args);
20147
0
    va_end(args);
20148
0
}
20149
20150
void ImGui::DebugLogV(const char* fmt, va_list args)
20151
0
{
20152
0
    ImGuiContext& g = *GImGui;
20153
0
    const int old_size = g.DebugLogBuf.size();
20154
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
20155
0
    g.DebugLogBuf.appendfv(fmt, args);
20156
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
20157
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
20158
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
20159
0
}
20160
20161
void ImGui::ShowDebugLogWindow(bool* p_open)
20162
0
{
20163
0
    ImGuiContext& g = *GImGui;
20164
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20165
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
20166
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
20167
0
    {
20168
0
        End();
20169
0
        return;
20170
0
    }
20171
20172
0
    CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
20173
0
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
20174
0
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
20175
0
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
20176
0
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
20177
0
    SameLine(); if (CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper)) { g.DebugLogClipperAutoDisableFrames = 2; } if (IsItemHovered()) SetTooltip("Clipper log auto-disabled after 2 frames");
20178
    //SameLine(); CheckboxFlags("Selection", &g.DebugLogFlags, ImGuiDebugLogFlags_EventSelection);
20179
0
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
20180
0
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
20181
0
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
20182
20183
0
    if (SmallButton("Clear"))
20184
0
    {
20185
0
        g.DebugLogBuf.clear();
20186
0
        g.DebugLogIndex.clear();
20187
0
    }
20188
0
    SameLine();
20189
0
    if (SmallButton("Copy"))
20190
0
        SetClipboardText(g.DebugLogBuf.c_str());
20191
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
20192
20193
0
    ImGuiListClipper clipper;
20194
0
    clipper.Begin(g.DebugLogIndex.size());
20195
0
    while (clipper.Step())
20196
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
20197
0
        {
20198
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
20199
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
20200
0
            TextUnformatted(line_begin, line_end);
20201
0
            ImRect text_rect = g.LastItemData.Rect;
20202
0
            if (IsItemHovered())
20203
0
                for (const char* p = line_begin; p <= line_end - 10; p++)
20204
0
                {
20205
0
                    ImGuiID id = 0;
20206
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
20207
0
                        continue;
20208
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
20209
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
20210
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
20211
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
20212
0
                        DebugLocateItemOnHover(id);
20213
0
                    p += 10;
20214
0
                }
20215
0
        }
20216
0
    if (GetScrollY() >= GetScrollMaxY())
20217
0
        SetScrollHereY(1.0f);
20218
0
    EndChild();
20219
20220
0
    End();
20221
0
}
20222
20223
//-----------------------------------------------------------------------------
20224
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
20225
//-----------------------------------------------------------------------------
20226
20227
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
20228
20229
void ImGui::DebugLocateItem(ImGuiID target_id)
20230
0
{
20231
0
    ImGuiContext& g = *GImGui;
20232
0
    g.DebugLocateId = target_id;
20233
0
    g.DebugLocateFrames = 2;
20234
0
}
20235
20236
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
20237
0
{
20238
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
20239
0
        return;
20240
0
    ImGuiContext& g = *GImGui;
20241
0
    DebugLocateItem(target_id);
20242
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
20243
0
}
20244
20245
void ImGui::DebugLocateItemResolveWithLastItem()
20246
0
{
20247
0
    ImGuiContext& g = *GImGui;
20248
0
    ImGuiLastItemData item_data = g.LastItemData;
20249
0
    g.DebugLocateId = 0;
20250
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
20251
0
    ImRect r = item_data.Rect;
20252
0
    r.Expand(3.0f);
20253
0
    ImVec2 p1 = g.IO.MousePos;
20254
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
20255
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
20256
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
20257
0
}
20258
20259
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
20260
void ImGui::UpdateDebugToolItemPicker()
20261
167k
{
20262
167k
    ImGuiContext& g = *GImGui;
20263
167k
    g.DebugItemPickerBreakId = 0;
20264
167k
    if (!g.DebugItemPickerActive)
20265
167k
        return;
20266
20267
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20268
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
20269
0
    if (IsKeyPressed(ImGuiKey_Escape))
20270
0
        g.DebugItemPickerActive = false;
20271
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
20272
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
20273
0
    {
20274
0
        g.DebugItemPickerBreakId = hovered_id;
20275
0
        g.DebugItemPickerActive = false;
20276
0
    }
20277
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
20278
0
        if (change_mapping && IsMouseClicked(mouse_button))
20279
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
20280
0
    SetNextWindowBgAlpha(0.70f);
20281
0
    if (!BeginTooltip())
20282
0
        return;
20283
0
    Text("HoveredId: 0x%08X", hovered_id);
20284
0
    Text("Press ESC to abort picking.");
20285
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
20286
0
    if (change_mapping)
20287
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
20288
0
    else
20289
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
20290
0
    EndTooltip();
20291
0
}
20292
20293
// [DEBUG] Stack Tool: update queries. Called by NewFrame()
20294
void ImGui::UpdateDebugToolStackQueries()
20295
167k
{
20296
167k
    ImGuiContext& g = *GImGui;
20297
167k
    ImGuiStackTool* tool = &g.DebugStackTool;
20298
20299
    // Clear hook when stack tool is not visible
20300
167k
    g.DebugHookIdInfo = 0;
20301
167k
    if (g.FrameCount != tool->LastActiveFrame + 1)
20302
167k
        return;
20303
20304
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
20305
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
20306
11
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
20307
11
    if (tool->QueryId != query_id)
20308
0
    {
20309
0
        tool->QueryId = query_id;
20310
0
        tool->StackLevel = -1;
20311
0
        tool->Results.resize(0);
20312
0
    }
20313
11
    if (query_id == 0)
20314
11
        return;
20315
20316
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
20317
0
    int stack_level = tool->StackLevel;
20318
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20319
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
20320
0
            tool->StackLevel++;
20321
20322
    // Update hook
20323
0
    stack_level = tool->StackLevel;
20324
0
    if (stack_level == -1)
20325
0
        g.DebugHookIdInfo = query_id;
20326
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20327
0
    {
20328
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
20329
0
        tool->Results[stack_level].QueryFrameCount++;
20330
0
    }
20331
0
}
20332
20333
// [DEBUG] Stack tool: hooks called by GetID() family functions
20334
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
20335
0
{
20336
0
    ImGuiContext& g = *GImGui;
20337
0
    ImGuiWindow* window = g.CurrentWindow;
20338
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20339
20340
    // Step 0: stack query
20341
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
20342
0
    if (tool->StackLevel == -1)
20343
0
    {
20344
0
        tool->StackLevel++;
20345
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
20346
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
20347
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
20348
0
        return;
20349
0
    }
20350
20351
    // Step 1+: query for individual level
20352
0
    IM_ASSERT(tool->StackLevel >= 0);
20353
0
    if (tool->StackLevel != window->IDStack.Size)
20354
0
        return;
20355
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
20356
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
20357
20358
0
    switch (data_type)
20359
0
    {
20360
0
    case ImGuiDataType_S32:
20361
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
20362
0
        break;
20363
0
    case ImGuiDataType_String:
20364
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
20365
0
        break;
20366
0
    case ImGuiDataType_Pointer:
20367
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
20368
0
        break;
20369
0
    case ImGuiDataType_ID:
20370
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
20371
0
            return;
20372
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
20373
0
        break;
20374
0
    default:
20375
0
        IM_ASSERT(0);
20376
0
    }
20377
0
    info->QuerySuccess = true;
20378
0
    info->DataType = data_type;
20379
0
}
20380
20381
static int StackToolFormatLevelInfo(ImGuiStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
20382
0
{
20383
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
20384
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
20385
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
20386
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
20387
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
20388
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
20389
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
20390
0
        return (*buf = 0);
20391
#ifdef IMGUI_ENABLE_TEST_ENGINE
20392
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
20393
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
20394
#endif
20395
0
    return ImFormatString(buf, buf_size, "???");
20396
0
}
20397
20398
// Stack Tool: Display UI
20399
void ImGui::ShowStackToolWindow(bool* p_open)
20400
0
{
20401
0
    ImGuiContext& g = *GImGui;
20402
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20403
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
20404
0
    if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
20405
0
    {
20406
0
        End();
20407
0
        return;
20408
0
    }
20409
20410
    // Display hovered/active status
20411
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20412
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20413
0
    const ImGuiID active_id = g.ActiveId;
20414
#ifdef IMGUI_ENABLE_TEST_ENGINE
20415
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
20416
#else
20417
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
20418
0
#endif
20419
0
    SameLine();
20420
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
20421
20422
    // CTRL+C to copy path
20423
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
20424
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
20425
0
    SameLine();
20426
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
20427
0
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
20428
0
    {
20429
0
        tool->CopyToClipboardLastTime = (float)g.Time;
20430
0
        char* p = g.TempBuffer.Data;
20431
0
        char* p_end = p + g.TempBuffer.Size;
20432
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
20433
0
        {
20434
0
            *p++ = '/';
20435
0
            char level_desc[256];
20436
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
20437
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
20438
0
            {
20439
0
                if (level_desc[n] == '/')
20440
0
                    *p++ = '\\';
20441
0
                *p++ = level_desc[n];
20442
0
            }
20443
0
        }
20444
0
        *p = '\0';
20445
0
        SetClipboardText(g.TempBuffer.Data);
20446
0
    }
20447
20448
    // Display decorated stack
20449
0
    tool->LastActiveFrame = g.FrameCount;
20450
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
20451
0
    {
20452
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
20453
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
20454
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
20455
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
20456
0
        TableHeadersRow();
20457
0
        for (int n = 0; n < tool->Results.Size; n++)
20458
0
        {
20459
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
20460
0
            TableNextColumn();
20461
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
20462
0
            TableNextColumn();
20463
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
20464
0
            TextUnformatted(g.TempBuffer.Data);
20465
0
            TableNextColumn();
20466
0
            Text("0x%08X", info->ID);
20467
0
            if (n == tool->Results.Size - 1)
20468
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
20469
0
        }
20470
0
        EndTable();
20471
0
    }
20472
0
    End();
20473
0
}
20474
20475
#else
20476
20477
void ImGui::ShowMetricsWindow(bool*) {}
20478
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
20479
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
20480
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
20481
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
20482
void ImGui::DebugNodeFont(ImFont*) {}
20483
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
20484
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
20485
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
20486
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
20487
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
20488
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
20489
20490
void ImGui::DebugLog(const char*, ...) {}
20491
void ImGui::DebugLogV(const char*, va_list) {}
20492
void ImGui::ShowDebugLogWindow(bool*) {}
20493
void ImGui::ShowStackToolWindow(bool*) {}
20494
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
20495
void ImGui::UpdateDebugToolItemPicker() {}
20496
void ImGui::UpdateDebugToolStackQueries() {}
20497
20498
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
20499
20500
//-----------------------------------------------------------------------------
20501
20502
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
20503
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
20504
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
20505
#include "imgui_user.inl"
20506
#endif
20507
20508
//-----------------------------------------------------------------------------
20509
20510
#endif // #ifndef IMGUI_DISABLE